I am writing this function for a J2ME application, so I don't have some of the more advanced / modern Java classes available to me. I am getting java.lang.ArrayIndexOutOfBoundsException
on this. So, apparently either it doesn't like the way I've initialized the newChars
array, or I'm not doing something correctly when calling System.arraycopy
.
/*
* remove any leading and trailing spaces
*/
public static String trim(String str) {
char[] chars = str.toCharArray();
int len = chars.length;
// leading
while ( (len > 0 ) && ( chars[0] == ' ' ) ) {
char[] newChars = new char[] {}; // initialize empty array
System.arraycopy(chars, 1, newChars, 0, len - 1);
chars = newChars;
len = chars.length;
}
// TODO: trailing
return chars.toString();
}
The replaceAll() method of the String class replaces each substring of this string that matches the given regular expression with the given replacement. You can remove white spaces from a string by replacing " " with "".
In Java, we can use regex \\s+ to match whitespace characters, and replaceAll("\\s+", " ") to replace them with a single space.
The simple way to trim leading and trailing whitespace is to call String.trim()
. With Java 11 and later, you can also use String.strip()
which uses a different interpretation of what "white space" means1.
If you just want to trim just leading and trailing spaces (rather than all leading and trailing whitespace), there is an Apache commons method called StringUtils.strip(String, String)
that can do this; call it with " "
as the 2nd argument.
Your attempted code has a number of bugs, and is fundamentally inefficient. If you really want to implement this yourself, then you should:
String.substring(from, end)
to create a new string containing the characters you want to keep.This approach avoids copying any characters2.
1 - The different meanings are explained in the respective javadocs. Alternatively, read the answers to Difference between String trim() and strip() methods in Java 11.
2 - Actually, that depends on the implementation of String
. For some implementations there will be no copying, for others a single copy is made. But either is an improvement on your approach, which entails a minimum of 2 copies, and more if there are any characters to trim.
String.trim()
is very old, at least to java 1.3. You don't have this?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With