Help on how to get the last word of a string and append to the beginning using java

1

I have a full name: Jais Pereira Guedes Godofredo

The example below, I get the last word, but how to print with this result: Godofredo, Jais Pereira Guedes

public class Aula1{

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        String nomeCompleto = "Jais Pereira Guedes Godofredo";
        String[] split = nomeCompleto.split(" ");
        String resultado = split[split.length - 1];
        System.out.println(resultado );
    }
}
    
asked by anonymous 02.01.2018 / 15:56

3 answers

3

Hi @AmandaRJ. I already had this doubt, see if it helps you, I solved it this way:

 *
 * @author marcia
 */
public class Aula1{

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        String nomeCompleto = "Jais Pereira Guedes Godofredo"; // Recebo o nome a ser tratado  
        int posicao = 0; // Posição do nome [0,1,2,3...], o nome está na posição 0  
        for (int i = 0; i < nomeCompleto.length(); i++) {
            if (nomeCompleto.charAt(i) == ' ') {
                posicao = i;
            }
        }
        System.out.println(nomeCompleto.substring(posicao, nomeCompleto.length()) + ", " + nomeCompleto.substring(0, posicao));
    }
}
    
02.01.2018 / 16:28
4
    String sentenca = "Jais Pereira Guedes Godofredo";
    int index= sentenca.lastIndexOf(" ");
    String restoSentenca = (sentenca.substring(0, index));
    String ultimaPalavra = (sentenca.substring(index+1));
    String novaSentenca = ultimaPalavra + ", " + restoSentenca;
    System.out.println(novaSentenca);

example - ideone

    
02.01.2018 / 16:32
-1

Use lastIndexOf and then substring

Here are some examples:

link

link

Examples:

import java.io.*;
public class Test {

public static void main(String args[]) {

  String Str = new String("Welcome to Tutorialspoint.com");

  System.out.print("Return Value :" );

  System.out.println(Str.substring(10) );


}
}

import java.io.*;
public class Test {

public static void main(String args[]) {

  String Str = new String("Welcome to Tutorialspoint.com");

  System.out.print("Found Last Index :" );

  System.out.println(Str.lastIndexOf( 'o' ));

}
}

Source: www.tutorialspoint.com/java

    
02.01.2018 / 16:09