Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question
 
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. –  David Wallace 7 mins ago
 
Do you need to use somware array with bob dylan and johny cash or is it only temporary array to create one with bob dylan johny cash elements? –  Pshemo 5 mins ago

2 Answers

Using StringUtils.join method in apache common lang.

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

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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.