Get the first letter of the last name and last name?

Asked

Viewed 3,476 times

2

I am using the code below to get the first letter of the name and surname.

It’s working, but I see the following problem for a longer name:

Example:

Carlos Eduardo Martins Dutra do Rego

public static void main(String[] args) {

    String nome = "Carlos Eduardo Martins Dutra do Rego";
    String primeiraLetraNomeSobrenome = "";
    for (char letra : nome.toCharArray()) {
        if (Character.isUpperCase(letra)) {
            primeiraLetraNomeSobrenome += letra;
        }
    }
    System.out.println("resultado: "+ primeiraLetraNomeSobrenome);
}

I receive: CEMDR

I wanted to catch the first and the last CR. Would you have any tips for me to fix this?

2 answers

6

Personally, I’d make your code a lot easier this way. Obviously you need to validate if the received string is not null or empty, but that’s just detail, the focus here is the implementation.

String nome = "Carlos Eduardo Martins Dutra do Rego";
String[] array = nome.split(" ");
// ^ Cria um array onde cada elemento é uma das palavras

String resultado = String.valueOf(array[0].charAt(0));
// ^ Captura a primeira letra da primeira palavra do array    

if(array.length > 1)
    resultado += array[array.length - 1].charAt(0);
    // ^ Captura a primeira letra da última palavra, apenas se tiver mais de uma palavra

System.out.println("resultado: "+ resultado);

If you just want to complement your current method, you only need to get the first and last character of the string produced with charAt(0) and charAt(tamanhoDaString - 1).

String nome = "Carlos Eduardo Martins Dutra do Rego";
String primeiraLetraNomeSobrenome = "";
for (char letra : nome.toCharArray()) {
    if (Character.isUpperCase(letra)) {
        primeiraLetraNomeSobrenome += letra;
    }
}

String primeiraUltima = primeiraLetraNomeSobrenome.charAt(0) + 
                primeiraLetraNomeSobrenome.charAt(primeiraLetraNomeSobrenome.length() -1);

System.out.println("resultado: "+ primeiraUltima);
  • 2

    The algorithm is naive, several things can go wrong, but it is not your problem, what was asked is answered, the first is a little better, to make a robust would be even more complex.

3


To get the first letter of the last name you can use the method lastIndexOf() class String:

String nome = "Carlos Eduardo Martins Dutra do Rego";
int posicaoUltimoEspaco = nome.lastIndexOf(" ");
String primeiraLetraUltimoNome = nome.substring(posicaoUltimoEspaco + 1, posicaoUltimoEspaco + 2);

In doing nome.lastIndexOf(" "), the position of the last space character will be returned.

So:

String primeiraLetraUltimoNome = nome.substring(posicaoUltimoEspaco + 1, posicaoUltimoEspaco + 2);
  • posicaoUltimoEspaco + 1 : The position of the last space is the space character itself. Somo +1 to pick from the next character.

  • posicaoUltimoEspaco + 2 : Continuing the reasoning of the above item, I add +2 to indicate that I want until the next caracetere.


To get the first letter of the first name just do:

String nome = "Carlos Eduardo Martins Dutra do Rego";
String primeiraLetra = Character.toString(nome.charAt(0));

EDIT

The method lastIndexOf() returns -1 if you do not find any record of the String searched. It is necessary to do a small check before:

int posicaoUltimoEspaco = nome.lastIndexOf(" ");
String primeiraLetraUltimoNome = "";
if(posicaoUltimoEspaco > 0) {
    primeiraLetraUltimoNome = nome.substring(posicaoUltimoEspaco + 1, posicaoUltimoEspaco + 2);
}
  • If the name is only "Carlos", the exit will be C C. That’s right?

  • @jbueno altered

  • 1

    @Igorventurelli thanks for the didactic that helped me a lot.

  • I still don’t get it, if the name is just Carlos the output must be an empty string?

  • @jbueno no. This was the simplest implementation I found, since the focus of the question is to identify the initials and not the concatenation itself. The correct/elegant form would be to concatenate with StringBuilder and just call the append() if the result of lastIndexOf() for >0.

Browser other questions tagged

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