Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing spaces at the end of a string in java [duplicate]

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...

like image 434
diminuta Avatar asked Aug 24 '12 09:08

diminuta


People also ask

How do you remove duplicates and spaces in a string in Java?

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 ' ' .

How do you remove extra spaces from a string?

Use JavaScript's string. replace() method with a regular expression to remove extra spaces. The dedicated RegEx to match any whitespace character is \s .

How do you ignore spaces in Java?

You can implicitly ignore them by just removing them from your input text. Therefore replace all occurrences with "" (empty text): fullName = fullName. replaceAll(" ", "");


1 Answers

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.

like image 62
Nicola Musatti Avatar answered Nov 05 '22 18:11

Nicola Musatti