如何在整个字符串中获取特定单词?

时间:2015-07-09 07:20:24

标签: android string

我正在创建和随机生成任何类别的Android应用程序,我想得到给定的随机类别字。这是示例字符串

  

String =“类别以字母J开头的动物”;

  

String =“类别以字母V”开头的颜色;

我需要生成每个随机字符串动物颜色这个词

4 个答案:

答案 0 :(得分:1)

您可以使用正则表达式。

Matcher m = Pattern.compile("\\bcategory\\s+(\\S+)").matcher(str);
while(m.find()) {
   System.out.println(m.group(1));
 }

Matcher m = Pattern.compile("(?<=\\bcategory\\s)\\S+").matcher(str);
while(m.find()) {
   System.out.println(m.group());
 }

答案 1 :(得分:1)

不是那么先进的解决方案,但很容易理解:

    public void findCategory() {
    String string = "The category Colors that starts with a letter V";

    String[] split = string.split(" ");
    int i;

    for (i = 0; i < split.length; i++) {
        if ("category".equals(split[i])) {
            break;
        }
    }

    System.out.println(split[i + 1]);
}

答案 2 :(得分:0)

请使用匹配器和模式 -

 String input = "The category Animals that starts with a letter J";
            Matcher m1 = Pattern.compile("^The category (.*) that starts with a letter (.*)$").matcher(input);
            if(m1.find()) {
                String _thirdWord = m1.group(1); // Animals
                String _lastWord  = m1.group(2); // J
                System.out.println("Third word : "+_thirdWord);
                System.out.println("Last Word : "+_lastWord);

            }

答案 3 :(得分:0)

使用它,它可能会解决您的问题

String string = "The category Colors that starts with a letter V";

String[] ar = string.split(" ");

System.out.println(ar[2]);