Skip to content
Advertisement

Getting only the first name in an array

I have an array list like this: ArrayList names = new ArrayList<>(); that stores people’s first and last names when they are entered in different textbooks.

So when prompted to Joe Biden would be element number 1 then Barack Obama would be element number 2 in the array list. My question is that if it is possible to only get their first names like Joe from the array without getting Biden also?

Advertisement

Answer

Yes you could just do

names.get(0).split("\s+")[0]  //this would get you "Joe"

to get last name possibly do

names.get(0).split("\s+")[1] //this would get you "Biden"

This way completely relies on the fact that you have a space in between their first and last name. and obviously edit the 0 to whatever index you would like.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement