[英]Split more complicated String to get the numbers in Java
I have a given String that represents the age in format: 我有一个给定的String,它以格式表示年龄:
"YY yr MM mo" or “ YY YY MM mo”或
"Y yr MM mo" or “ Y MM MM”或
"YY yr M mo" or “ YY YY M mo”或
"Y yr M mo" “你M M”
where YY/Y represent years (example: 5 or 44) and MM/M represent months (example: 2 or 11). 其中YY / Y代表年份(例如:5或44),而MM / M代表月份(例如:2或11)。 Just to be clear, I give example of a String pAge = "11 yr 5 mo" or String pAge = "4 yr 10 mo".
为了清楚起见,我举一个String pAge =“ 11 yr 5 mo”或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. 现在,我想分割此String并将其仅打印为数字,在表示年龄的月份和月份的两个单独的文本字段中。 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 . 您提出的所有4种情况都是一样的 。 All of them have 4 parts delimited by a space.
它们都有4个由空格分隔的部分。
This means that you can use .split()
for all 4 cases: 这意味着您可以在所有4种情况下使用
.split()
:
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];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.