Remove last character from a string when the character is a blank

Asked

Viewed 1,211 times

0

Good afternoon.

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

"Jonas Barros Santos"

Must appear : 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 wanted some help to solve 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);
    }

3 answers

1


  • 1

    worked as I needed. Thank you

0

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

0

It’s simple Amanda, as @Marconi commented, applying a trim on the right side of your string, the white space is deleted regardless of how many have, so you can use your code that will not error by accessing a non-existent index in the string. Stay 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);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.