【发布时间】:2019-09-13 22:19:47
【问题描述】:
我有以下文字:
"The data of Branch 1 are correct - true"
"data of Branch 4 are correct - false"
对于每个文本,我想获取分支的数量和布尔值 true 或 false。每行的结果将是:
1 true
4 false
我该怎么做?
【问题讨论】:
-
到目前为止你有什么尝试?
标签: java
我有以下文字:
"The data of Branch 1 are correct - true"
"data of Branch 4 are correct - false"
对于每个文本,我想获取分支的数量和布尔值 true 或 false。每行的结果将是:
1 true
4 false
我该怎么做?
【问题讨论】:
标签: java
你可以用不同的方式来做。
在这种情况下最简单的方法之一是拆分字符串并获取第五个和第九个元素
String sentence = "The data of Branch 1 are correct - true";
String[] elements = string.split(" "); then get relevant elements of array.
// elements[4] is the string 1 (you can convert it to int if necessary with Integer.parseInt(elements[4]) )
// elements[8] is the string true (you can convert it to boolean if necessary with Boolean.parseBoolean(elements[4]) )
其他可能性是:
知道可以创建类似于以下的方法来打印相关部分:
public static void printRelevant(String string) {
String[] elements = string.split(" ");
System.out.println(elements[4] + " " + elements[8]);
}
...
pritnRelevant("The data of Branch 1 are correct - true");
printRelevant("The data of Branch 4 are correct - false");
感谢 Sotirios 的 cmets,我看到这两个短语不相等。 所以需要使用正则表达式来提取相关部分:
public static void printRelevant(String string) {
Pattern numberPattern = Pattern.compile("[0-9]+");
Pattern booleanPattern = Pattern.compile("true|false");
Matcher numberMatcher = numberPattern.matcher(string);
Matcher booleanMatcher = booleanPattern.matcher(string);
if (numberMatcher.find() && booleanMatcher.find()) {
return numberMatcher.group(0) + " " + booleanMatcher.group(0);
}
throw new IllegalArgumentException("String not valid");
}
【讨论】:
步骤一:使用String按空格分割将所有元素放入数组中
第 2 步:找到您感兴趣的元素的索引
第 3 步:将每个元素 String 解析为所需的类型(Integer 和 Boolean)
这应该让你开始!
【讨论】:
如果你总是有相同的输入字符串“模式”,你可以这样做:
input = "The data of Branch 1 are correct - true";
// split by space
String [] words = input.split(" ");
// take the values (data) that you need.
System.out.println(words[4] + " " + words[8]);
// also you can cast values to the needed types
类似的东西。 最好的方法可能是使用正则表达式从输入字符串中获取所需的数据。
【讨论】:
input不仅仅是"The data of Branch 1 are correct - true";,还有"data of Branch 4 are correct - false";。对于该示例,words[8] 将超出范围。