0

I have an array with each element containing first and second names,

 eg array[0] = bob dylan
 array[1] = johny cash

I want to take those names, split them, and assign the first name to element[0] of a new array, and the surname to element[1] of the new array,

 eg newArray[0] = bob
 newArray[1] = dylon
 newArray[2] = johny
 newArray[3] = cash

Here's where I'm at so far:

 String name;
 for( int i = 0; i < array.length; i++ ){
 System.out.println( "Enter the singers First name and Surname:" );
 name = s.nextLine();
 array[ i ] = name;
 }

I've got both arrays ready but i'm unsure whether I need to take the array elements and assign them to a string 1 by 1, then split them and put them in a new array, or perhaps theres a way to look at each element of a string[] and split them and assign to a new array without needing to use seperate strings. Many Thanks

asked Nov 20, 2013 at 2:32
1
  • You could have a look at the Javadoc for the String class, in particular the split method, and also the Javadoc for the List interface. Commented Nov 20, 2013 at 2:38

2 Answers 2

1

Use a combination of String.split() and the Java Collections package to deal with the unknown array size.

String[] names = new String[] {"bob dylan", "johny cash"};
List<String> splitNames = new ArrayList<>();
for (String name : names) {
 splitNames.addAll(Arrays.asList(name.split(" ")));
}

From here, you can iterate through each name in your String array and split it based on a regex, such as a space. You can then add the result to your List of Strings which would contain:

"bob", "dylan", "johny", "cash"

By using Collections, you do not need to know the size of your names String array, and you can handle cases where a name does not have multiple parts.

If you need to convert the List back to an array:

String[] splitNamesArray = splitNames.toArray(new String[splitNames.size()]);
answered Nov 20, 2013 at 2:39
0
1

Using StringUtils.join method in apache common lang.

String[] newArray = StringUtils.join(array," ").split("\\s+");
answered Nov 20, 2013 at 2:39

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.