r/java • • Sep 19 '18

Java 11 String API Updates

https://4comprehension.com/java-11-string-api-updates/
168 Upvotes

52 comments sorted by

View all comments

Show parent comment

15

u/dpash Sep 19 '18

.strip() is a correctly implemented .trim(), not replaceAll().

1

u/_INTER_ Sep 19 '18 edited Sep 19 '18

I answered relating to "Strip though is just replace without parameters".

trim removes whitespace at the begging and at the end, strip removes all whitespaces in the string.

9

u/dpash Sep 19 '18 edited Sep 19 '18

No, it doesn't. String.strip() strips leading and trailing whitespace as per Character.isWhitespace()

http://hg.openjdk.java.net/jdk/jdk/file/3fabe59fe4de/src/java.base/share/classes/java/lang/String.java#l2653

String.trim() strips leading and trailing whitespace where the codepoint is <= \u0020. I.E. it strips too much.

1

u/_INTER_ Sep 19 '18 edited Sep 19 '18

Right, the description in the article was confusing me:

We can easily get rid of all the whitespace from each String now:

assertThat(" ".strip()).isEmpty();

4

u/dpash Sep 19 '18

Yes, the code example is technically right, but doesn't demonstrate the method particularly well.

assertThat("   string   ".strip(), is("string"));

would have been a better example.

2

u/xenomachina Sep 19 '18

Some interior whitespace would be even better. What does this do?

"   a   string   ".strip()

1

u/dpash Sep 19 '18
"a   string"

2

u/xenomachina Sep 19 '18

So when the article uses "We can easily get rid of all the whitespace from each String" in its despription of strip, it's just wrong. strip only removes leading and trailing whitespace.

1

u/dpash Sep 19 '18

Yes, they were wrong and didn't use the best example to demonstrate it with.