Anonymous user
Strip whitespace from a string/Top and tail: Difference between revisions
Strip whitespace from a string/Top and tail (view source)
Revision as of 12:04, 4 March 2021
, 3 years ago→{{header|Java}}: Rework a tiny bit. Remove raw `trim`. Add some help text.
(→{{header|Kotlin}}: Add comments. Add limiters to better visualize output.) |
(→{{header|Java}}: Rework a tiny bit. Remove raw `trim`. Add some help text.) |
||
Line 1,028:
=={{header|Java}}==
Java offers <code>String.trim</code>. However, this function only strips out ASCII control characters. As such it should generally be avoided for processing text.
Rather, the function <code>Character.isWhitespace</code> should be used to strip out any Unicode whitespaces. Note that the Java implementation slightly deviates from the strict Unicode definition: For example, non-breaking spaces are not considered whitespace by Java. This is fine for stripping leading/trailing whitespaces, as a non-breaking space generally should not appear there, but is something to keep in mind.
Left trim and right trim taken from [http://www.fromdev.com/2009/07/playing-with-java-string-trim-basics.html here].
public class Trims{▼
public static String ltrim(String s){▼
int i = 0;▼
while (i < s.length() && Character.isWhitespace(s.charAt(i))){▼
i++;▼
}▼
return s.substring(i);▼
}▼
▲<lang java>public class Trims{
public static String rtrim(String s){▼
public static
▲ int i = 0;
while (i > 0 && Character.isWhitespace(s.charAt(i))){▼
▲ while (i < s.length() && Character.isWhitespace(s.charAt(i))){
▲ return s.substring(i);
}▼
▲ }
int i = s.length() - 1;
▲ while (i > 0 && Character.isWhitespace(s.charAt(i))){
▲ }
return s.substring(0, i + 1);
▲ }
return rtrim(ltrim(s));
}
public static void main(String[] args){
String s = " \t \r \n String with spaces \u2009 \t \r \n ";
System.out.
System.out.
System.out.
}
}</lang>
|