简体   繁体   中英

How to split a String array into separate int and String arrays?

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[].

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM