Strip whitespace from a string/Top and tail: Difference between revisions

→‎{{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].
<code>Character.isWhitespace()</code> returns true if the character given is one of the following [[Unicode]] characters: '\u00A0', '\u2007', '\u202F', '\u0009', '\u000A', '\u000B', '\u000C', '\u000D', '\u001C', '\u001D', '\u001E', or '\u001F'.
<lang java>
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 intString i =ltrim(String s.length() - 1;{
int i = 0;
while (i > 0 && Character.isWhitespace(s.charAt(i))){
while (i < s.length() && Character.isWhitespace(s.charAt(i))){
i--;
} i++;
return s.substring(0, i + 1);}
return s.substring(i);
}
}
 
public static String ltrimrtrim(String s) {
int i = s.length() - 1;
while (i > 0 && Character.isWhitespace(s.charAt(i))){
i++--;
}
return s.substring(0, i + 1);
}
 
public static String rtrimtrim(String s) {
return rtrim(ltrim(s));
}
 
public static void main(String[] args){
String s = " \t \r \n String with spaces \u2009 \t \r \n ";
System.out.printlnprintf("[%s]\n", ltrim(s));
System.out.printlnprintf("[%s]\n", rtrim(s));
System.out.printlnprintf("[%s.]\n", trim(s)); //trims both ends
}
}</lang>