Possible Duplicate:
Strip Leading and Trailing Spaces From Java String
When I import data to an application I need to get rid of the spaces at the end of certain strings but not those at the beginning, so I can't use trim()... I've set up a method:
public static String quitarEspaciosFinal(String cadena) {
    String[] trozos = cadena.split(" ");
    String ultimoTrozo = trozos[trozos.length-1];
    return cadena.substring(0,cadena.lastIndexOf(ultimoTrozo.charAt(ultimoTrozo.length()-1))+1);
    }
where cadena is the string I have to transform...
So, if cadena = " 1234 " this method would return " 1234"...
I'd like to know if there's a more efficient way to do this...
1. Using String. replaceAll() method. To remove duplicate whitespaces from a string, you can use the regular expression \s+ which matches with one or more whitespace characters, and replace it with a single space ' ' .
Use JavaScript's string. replace() method with a regular expression to remove extra spaces. The dedicated RegEx to match any whitespace character is \s .
You can implicitly ignore them by just removing them from your input text. Therefore replace all occurrences with "" (empty text): fullName = fullName. replaceAll(" ", "");
I'd do it like this:
public static String trimEnd(String s)
{
    if ( s == null || s.length() == 0 )
        return s;
    int i = s.length();
    while ( i > 0 &&  Character.isWhitespace(s.charAt(i - 1)) )
        i--;
    if ( i == s.length() )
        return s;
    else
        return s.substring(0, i);
}
It's way more verbose than using a regular expression, but it's likely to be more efficient.
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