Remove last character from a string, when the character is a blank space [duplicate]

0

Good afternoon.

I'm programming in java and I want to get the initials of a name, in case:

"Jonas Barros Santos"

You have to see: JS

The code I use does this, but if the person puts the name with space at the end, my code does not work, giving an exception.

"Jonas Barros Santos"

I would like help solving this problem.

 public static void main(String[] args) {
        // TODO code application logic here
        String nome = "Jonas Barros Santos ";
        String nomeAbrev = null;
        int posicaoUltimoEspaco = nome.lastIndexOf(" ");
        String primeiraLetraUltimoNome = "";
        if (posicaoUltimoEspaco > 0) {
            primeiraLetraUltimoNome = nome.substring(posicaoUltimoEspaco + 1, posicaoUltimoEspaco + 2);
        }
        String primeiraLetra = nome.substring(0, 1);
        nomeAbrev = primeiraLetra + primeiraLetraUltimoNome;
        System.out.println(nomeAbrev);
    }
    
asked by anonymous 09.05.2017 / 18:30

3 answers

1

Use the trim () function, for example, name.trim () takes the start and end space. link

    
09.05.2017 / 18:34
0

You can use trim () method that takes space only from the beginning and end of the string.

    
09.05.2017 / 18:35
0

It's simple Amanda, as @Marconi commented, by applying a trim to the right part of your string , whitespace is eliminated regardless of how many, so you can use your code that will not accuse error for accessing an index that does not exist in string . It looks like this:

String nome = "Jonas Barros Santos     ";
String nomeAbrev = "";
nomeAbrev = nome.replaceAll("\s+$","");
int posicaoUltimoEspaco = nomeAbrev.lastIndexOf(" ");
String primeiraLetraUltimoNome = "";
if (posicaoUltimoEspaco > 0) {
      primeiraLetraUltimoNome = nomeAbrev.substring(posicaoUltimoEspaco + 1, posicaoUltimoEspaco + 2);
}
String primeiraLetra = nomeAbrev.substring(0, 1);
nomeAbrev = primeiraLetra + primeiraLetraUltimoNome;
System.out.println(nomeAbrev);
    
09.05.2017 / 18:46