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

Content added Content deleted
(RPL: add section)
Line 1,152: Line 1,152:


=={{header|Java}}==
=={{header|Java}}==
Java has the ''trim'' and ''strip'' operations. Both will achieve a similar result.<br />

The ''trim'' method works on Unicode values under 0x20. Whereas, ''strip'' will remove all Unicode white-space characters.
<syntaxhighlight lang="java">
" abc".stripLeading()
</syntaxhighlight>
<syntaxhighlight lang="java">
"abc ".stripTrailing()
</syntaxhighlight>
<syntaxhighlight lang="java">
" abc ".strip()
</syntaxhighlight>
<syntaxhighlight lang="java">
" abc ".trim()
</syntaxhighlight>
For more control over what characters should be removed, you could implement your own methods.
<syntaxhighlight lang="java">
String removeLeading(String string, char... characters) {
int index = 0;
for (char characterA : string.toCharArray()) {
for (char characterB : characters) {
if (characterA != characterB)
return string.substring(index);
}
index++;
}
return string;
}
</syntaxhighlight>
<syntaxhighlight lang="java">
String removeTrailing(String string, char... characters) {
for (int index = string.length() - 1; index >= 0; index--) {
for (char character : characters) {
if (string.charAt(index) != character)
return string.substring(0, index + 1);
}
}
return string;
}
</syntaxhighlight>
<br />
An alternate demonstration<br />
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.
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.