Is there any way to give split()
to string
and on the same line get the position I want?
For example:
String nome = "Dan Lucio Prada";
String sobrenome = nome.split(" "); //aqui quero pegar só o sobrenome [Prada]
Is there any way to give split()
to string
and on the same line get the position I want?
For example:
String nome = "Dan Lucio Prada";
String sobrenome = nome.split(" "); //aqui quero pegar só o sobrenome [Prada]
All the answers are correct, but I find it interesting to add that, taking into account that the surname will always be the last word of string
, you can do the following:
String nome = "Dan Lucio Prada";
EscreverSobrenome(nome); // A saída será "Prada"
String nome2 = "Joaquim Pedro Soares da Silva";
EscreverSobrenome(nome2); // A saída será "Silva"
public String EscreverSobrenome(String nome){
sobrenome = nome.split(" ")[nome.split(" ").length - 1]; // Essa linha é a solução pro seu problema
System.out.println(sobrenome);
}
In this way no matter how many words you have, the variable sobrenome
will always receive the last word.
Have, do so:
String nome = "Dan Lucio Prada";
String sobronome = nome.split(" ")[2];
Of course this only works if the name has 3 words.
For registration and (perhaps) usefulness to someone, in this case there is no need to have to do split
of string . I do not know if it is mandatory to use split
or have the last name, but without using split
it is possible to do it in a single line, something like this:
sentence.substring(sentence.lastIndexOf(" ") + 1)
sentence.lastIndexOf(" ")
, as it is simply understood, will return the index of the last space in the statement. Then we add 1
, position of the next letter that is the first letter of the last name. With this information substring(int beginIndex)
, you'll start of this first letter of the name and will go to the end of the sentence / name, always returning the last word.
For example, this:
public static void main(final String[] args) {
final String dan = "Dan Lucio Prada";
System.out.println(lastWordFromSentence(dan));
final String bruno = "Bruno César";
System.out.println(lastWordFromSentence(bruno));
final String name = "Bruno";
System.out.println(lastWordFromSentence(name));
}
public static String lastWordFromSentence(final String sentence) {
return sentence.substring(sentence.lastIndexOf(" ") + 1);
}
Generate this result:
Prada
César
Bruno
It is suggested in cases that the use of split
is not mandatory:)
Yes, you can do this on a line:
System.out.println("Dan Lucio Prada".split(" ")[2]);
But it's much better to use more than one line and do it right:
String nome = "Dan Lucio Prada";
String[] partes = nome.split(" ");
System.out.println(partes[partes.length - 1]);
You can even do this in a row too but it's inefficient, so you'd better do it right.
See running on ideone .