Question

I have this code that I am trying to sort. Therefore, I want to split my array into one called ages, and the other called names. Here is what I have so far:

    String na = "Jones 14 \nAbrams 15 \nSmith 19 \nJones 9\nAlexander 22\nSmith 20\nSmith 17\nTippurt 42\nJones 2\nHerkman 12\nJones 11";
    String text[] = na.split("\\s+");

So far, this only splits the array at whitespace. I want my output to have all the numbers in ages[], and all the words in names[].

No correct solution

OTHER TIPS

You can split by the newline character first.

String lines = na.split("\n");

When looping through lines, split each line by whitespace, \\s+, to split each field on the current line.

for (String line : lines)
{
   String[] text = line.split("\\s+");
   // other processing
}

Then you can access the individual values and assign them to arrays or whatever you'd like. Your idea of storing 2 arrays would work fine, but I would create an array or a List of Person objects that are defined to hold your fields such as name and age.

Try this.

    String names[] = na.split("\\s*\\d+\\s*");
    String ages[] = na.split("\\s*\\D+\\s*");

You should fine tune it a bit but the idea should be OK.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top