【问题标题】:How to get specific word in a string in Java [duplicate]如何在Java中获取字符串中的特定单词[重复]
【发布时间】: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


【解决方案1】:

你可以用不同的方式来做。

在这种情况下最简单的方法之一是拆分字符串并获取第五个和第九个元素

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]) )

其他可能性是:

  • 使用正则表达式(查找数字并搜索单词 true false)
  • 使用位置(你知道数字总是在同一个位置开始,而布尔值总是在末尾)

知道可以创建类似于以下的方法来打印相关部分:

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");
}

【讨论】:

    【解决方案2】:

    步骤一:使用String按空格分割将所有元素放入数组中

    第 2 步:找到您感兴趣的元素的索引

    第 3 步:将每个元素 String 解析为所需的类型(IntegerBoolean

    这应该让你开始!

    【讨论】:

      【解决方案3】:

      如果你总是有相同的输入字符串“模式”,你可以这样做:

      
      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
      
      

      类似的东西。 最好的方法可能是使用正则表达式从输入字符串中获取所需的数据。

      【讨论】:

      • 您的答案因他们的示例输入而中断。
      • 如果我理解正确的评论 - 不。 Split() 返回一个字符串数组,它不会修改自己。
      • 他们的input不仅仅是"The data of Branch 1 are correct - true";,还有"data of Branch 4 are correct - false";。对于该示例,words[8] 将超出范围。
      猜你喜欢
      • 1970-01-01
      • 2019-05-17
      • 1970-01-01
      • 2018-08-14
      • 1970-01-01
      • 1970-01-01
      • 2019-05-16
      • 1970-01-01
      • 2010-09-20
      相关资源
      最近更新 更多