Ryan H
Ryan H

Reputation: 85

Java array split string

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

Upvotes: 0

Views: 5656

Answers (2)

hotforfeature
hotforfeature

Reputation: 2588

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()]);

Upvotes: 1

FUD
FUD

Reputation: 5184

Using StringUtils.join method in apache common lang.

String[] newArray = StringUtils.join(array," ").split("\\s+");

Upvotes: 1

Related Questions