Remove Whitespace from the Beginning and End of a String
suggest changeThe trim()
method returns a new String with the leading and trailing whitespace removed.
String s = new String(" Hello World!! ");
String t = s.trim(); // t = "Hello World!!"
If you trim
a String that doesn’t have any whitespace to remove, you will be returned the same String instance.
Note that the trim()
method has its own notion of whitespace, which differs from the notion used by the Character.isWhitespace()
method:
- All ASCII control characters with codes
U+0000
toU+0020
are considered whitespace and are removed bytrim()
. This includesU+0020 'SPACE'
,U+0009 'CHARACTER TABULATION'
,U+000A 'LINE FEED'
andU+000D 'CARRIAGE RETURN'
characters, but also the characters likeU+0007 'BELL'
. - Unicode whitespace like
U+00A0 'NO-BREAK SPACE'
orU+2003 'EM SPACE'
are not recognized bytrim()
.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents