简体   繁体   中英

Split more complicated String to get the numbers in Java

I have a given String that represents the age in format:
"YY yr MM mo" or
"Y yr MM mo" or
"YY yr M mo" or
"Y yr M mo"
where YY/Y represent years (example: 5 or 44) and MM/M represent months (example: 2 or 11). Just to be clear, I give example of a String pAge = "11 yr 5 mo" or String pAge = "4 yr 10 mo".
Now I'd like to split this String and print it only as a numbers in a two separate text fields that represents years and months in age. To get years I writing a function:

    String arr[] = pAge.split(" ", 2);
    return arr[0];

And another function to get months:

    int i = pAge.indexOf("yr", pAge.indexOf(" ") + 1);
    int k = pAge.indexOf(" ", pAge.indexOf(" ") + 4);
    String s = pAge.substring(i, k);
    return s.substring(s.lastIndexOf(" ") + 1);

So, first method looks nice and it's easy but is there is any simpler way to write the second function? Both are working well and giving a correct output.

All the 4 cases given by you are the same . All of them have 4 parts delimited by a space.

This means that you can use .split() for all 4 cases:

String[] tokens = pAge.split(" ");
int years = Integer.parseInt(tokens[0]);  //get first token
int months = Integer.parseInt(tokens[2]);  //get third token

How about this untested pseudo code:

String tokens[] = pAge.split(" ");

if (tokens.length != 4 || tokens[1] != "yr" || tokens[3] != "mo")
   throw new SyntaxError("pAge is not 'N yr N mo'");

String years = tokens[0];
String month = tokens[2];

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