[英]Extract comma separated list of number or words using Java
for example with the given input message: hello java 2017 ** 2020 world
例如,使用给定的输入消息:
hello java 2017 ** 2020 world
2017 , 2020
2017 , 2020
hello , java , world
hello , java , world
Here is my program: 这是我的程序:
public static void print(String message, int choice){
{
for (int i = 0; i < message.length();) {
if (message.indexOf(" ") != -1) {
System.out.print(message.substring(0, message.indexOf(" ")));
message = message.substring(message.indexOf(" ") + 1);
switch (choice) {
case 2: {
char c;
for (int k = 0; k < message.length(); k++) {
c = message.charAt(k);
if (Character.isDigit(c)) {
System.out.print(c+" , ");
}break;
}
}
case 3: {
for (int z = 0; z < message.length(); z++) {
char tr = message.charAt(z);
if (Character.isAlphabetic(tr)) {
System.out.print(tr);
break;
}
}
}
}
} else {
System.out.println(message);
break;
}
}
}
}
I want to do it without using split
, replace
, arrays
or a tokenizer
. 我想做到这一点而无需使用
split
, replace
, arrays
或tokenizer
。
Regex? 正则表达式?
You can match numbers with (\\\\d+)
in Java and words (assuming from your example that it will contain only alphabetical characters with ([a-zA-z]+)
您可以将Java中的
(\\\\d+)
与数字和单词进行匹配(假设您的示例中仅包含([a-zA-z]+)
字母字符,
Now you can go ahead and do the following: 现在,您可以继续执行以下操作:
public static void print(String message, int choice) {
switch (choice) {
case 2:
Pattern p = Pattern.compile("(\\d+)");
Matcher m = p.matcher(message);
while (m.find()) {
System.out.println(m.group());
}
break;
case 3:
Pattern p2 = Pattern.compile("([a-zA-z]+)");
Matcher m2 = p2.matcher(message);
while (m2.find()) {
System.out.println(m2.group());
}
break;
}
}
Instead of printing the groups, you can as well add them to a list for later use, etc. 您也可以将它们添加到列表中以供以后使用,而不是打印组。
However I suggest (as others did in the comments before) that you use the probably easier and faster tools Java already offers to you. 但是,我建议(就像其他人在之前的评论中所做的那样)建议您使用Java已经提供给您的可能更简单,更快的工具。
Testing the above code with your example like this 用您的示例测试上述代码
public static void main(String[] args) {
String s = "hello java 2017 ** 2020 world";
print(s, 2);
System.out.println();
print(s, 3);
}
prints: 打印:
2017
2017年
20202020
hello
你好
javajava的
world世界
Again you can put those in a List or other type of collection for later use including the comma separation. 同样,您可以将它们放入列表或其他类型的集合中,以供以后使用,包括逗号分隔。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.