2

I have a list of names (first and last). I need find a way to split at the " " and ONLY print the last name to the console. I have this currently, but, of course, it's still printing the first name.

for (int i=0; i<players.size(); i++) { String s = players.get(i).toString(); for(String token:s.split(" ")) System.out.println(token); 
4
  • Please specify the language you want to use... That's what tags are for. Commented Oct 23, 2013 at 23:22
  • Create the token array, then print the last element. That is assuming the last name has no spaces in it. Sorry, that is a terrible assumption. Commented Oct 23, 2013 at 23:24
  • And that the names are entered firstname lastname Commented Oct 23, 2013 at 23:26
  • @andrew I think that is the only thing that is "given". Commented Oct 23, 2013 at 23:31

3 Answers 3

2

No need to use internal for loop. Change it as shown below.

for (int i=0; i<players.size(); i++) { String s = players.get(i).toString(); String [] token = s.split(" "); System.out.println(token[token.length -1]); } 
Sign up to request clarification or add additional context in comments.

10 Comments

Unless the name is Jack the Ripper. "Hello Mr. The!"
That won't work if a person has only one name (Cher, Prince, Elizabeth), nor will it work if the person has a double first name (Billy Ray Cyrus).
Yeah. It won't handle these cases. But going by what OP has posted I don't think he cares to handle these cases.
SO is meant to be a collaborative platform... Just doing my bit!
@Trying While I agree that the statement is unnecessary, I disagree with your reason as to why. The null-check is unnecessary because split doesn't return null array elements.
|
0

In Java, String.split() returns an array of tokens. Instead of iterating over the array and printing each one, store the array in a temporary variable (say String[] tokens) and just print the last one. (You can use tokens.length to find out how long the array is.)

Comments

0
for (int i=0; i<players.size(); i++) { String s = players.get(i).toString(); String[] str=s.split(" ") System.out.println(str[str.length-1]); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.