检查字符串是否包含特定单词

28

那么如何检查一个字符串中是否包含特定单词?

这是我的代码:

a.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            if(d.contains("Hey")){
                c.setText("OUTPUT: SUCCESS!"); 
            }else{
                c.setText("OUTPUT: FAIL!");  
            }
        }
    });

我遇到了一个错误。


阅读有关正则表达式(RegEx)的更多信息。 - Lingviston
2
检查部分看起来没问题。出了什么错误? - Ken Wolf
4
什么是错误?d代表什么?c代表什么? - Ant P
11个回答

60

并没有他们说的那么复杂,检查一下你不会后悔。

String sentence = "Check this answer and you can find the keyword with this code";
String search  = "keyword";

if ( sentence.toLowerCase().indexOf(search.toLowerCase()) != -1 ) {

   System.out.println("I found the keyword");

} else {

   System.out.println("not found");

}

如果你想的话,可以更改 toLowerCase()


1
感谢fthopkins的回答。虽然这是一个老问题,但我今天在工作中遇到了类似的情况。上面的代码搜索charsequence而不是单词。例如:如果我们只想捕获“keyword”而不是任何扩展名,如“keyword_1”,则上面的代码将无法工作。避免这种情况的一种方法是使用String contains函数搜索“ keyword ”(注意两侧的两个空格)-是否有更优雅的方法? - JavaTec
3
您需要使用正则表达式来正确地搜索单词,类似于m0skit0的回答(如果您经常使用相同的表达式,请参见该答案以使用已编译的表达式),您需要这样做:if (d.matches("\\bkeyword\\b")) {/*success*/}\b(在字符串中使用\\b转义反斜杠)匹配“单词边界”,即单词的边缘。与使用空格相比的优点是它可以正确地匹配像“句子中的关键字。”(句号而不是空格)甚至“关键字”(开头或结尾没有空格)等内容。 - Logan Pickup
1
感谢@LoganPickup - 我最终使用了\\b(那时是在十月),它运行良好。 - JavaTec
1
这段代码仅检查一个字符串是否包含另一个字符串。语义对于实际单词并不适用。"cheese" != "cheeseburger" 和 "cat" != "catalogue"。 - toniedzwiedz

12

.contains() 是非常有效的,也是一种良好的检查方式。

(http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#contains(java.lang.CharSequence))

由于您没有发布错误,我猜 d 要么是 null,要么您正在收到“无法引用在不同方法中定义的内部类中的非终局变量”错误。

为了确保它不是 null,在 if 语句中首先检查 null。如果是其他错误,请确保 d 声明为 final 或是你类的成员变量。对于 c 同样如此。


9

您可以使用正则表达式:

if (d.matches(".*Hey.*")) {
    c.setText("OUTPUT: SUCCESS!");
} else {
    c.setText("OUTPUT: FAIL!");  
}

.* -> 表示0个或多个任意字符

Hey -> 你想要的字符串

如果你需要经常检查这个正则表达式,最好将其编译成一个Pattern对象,并重复使用该Pattern实例进行检查。

private static final Pattern HEYPATTERN = Pattern.compile(".*Hey.*");
[...]
if (HEYPATTERN.matcher(d).matches()) {
    c.setText("OUTPUT: SUCCESS!");
} else {
    c.setText("OUTPUT: FAIL!");  
}

请注意,由于您没有指定要搜索独立单词的"Hey",因此这个表达式也会匹配例如"Heyburg"的字符串。 如果您只想匹配Hey作为一个完整的单词,您需要将正则表达式更改为 .*\\bHey\\b.*


哦,我的错。我忘记了 d = b.getText().toString(); 这一部分。 - WhiplashOne
我猜您是想将此评论作为 对您的问题 的评论编写。 - m0skit0
@m0skit0,我们能否忽略大小写进行匹配?也就是说,如果一个句子包含android/Android,它应该返回true。 - Karan Khurana
@KaranKhurana 这取决于 OP 实际想要或意味着什么是“word”。 - m0skit0
@m0skit0,OP 是什么? - Karan Khurana

5

截至目前为止,其他答案似乎检查的是子字符串而不是单词。这是一个重要的区别。

这篇文章的帮助下,我创建了这个简单的方法:

static boolean containsWord(String mainString, String word) {

    Pattern pattern = Pattern.compile("\\b" + word + "\\b", Pattern.CASE_INSENSITIVE); // "\\b" represents any word boundary.
    Matcher matcher = pattern.matcher(mainString);
    return matcher.find();
}

2

使用contains函数

String sentence = "Check this answer and you can find the keyword with this code";
String search = "keyword";

if (sentence.toLowerCase().contains(search.toLowerCase())) {

  System.out.println("I found the keyword..!");

} else {

  System.out.println("not found..!");

}

抱歉,我使用了 contains 而不是 indexOf。 - Lanil Marasinghe

2

如上所述,找到句子中的某个单词并不等同于找到charsequence,如果您不想玩弄正则表达式,则可以按以下方式完成。

boolean checkWordExistence(String word, String sentence) {
    if (sentence.contains(word)) {
        int start = sentence.indexOf(word);
        int end = start + word.length();

        boolean valid_left = ((start == 0) || (sentence.charAt(start - 1) == ' '));
        boolean valid_right = ((end == sentence.length()) || (sentence.charAt(end) == ' '));

        return valid_left && valid_right;
    }
    return false;
}

输出:

checkWordExistence("the", "the earth is our planet"); true
checkWordExistence("ear", "the earth is our planet"); false
checkWordExistence("earth", "the earth is our planet"); true

附注:在此之前,请确保已经过滤掉任何逗号或句号。


2

解决方案1:如果你想要从一个句子中搜索一组字符或者一个独立的单词。

String sentence = "In the Name of Allah, the Most Beneficent, the Most Merciful."
if (sentence.matches(".*Beneficent.*")) {return true;}
else{return false;}

解决方案-2:- 还有另一种可能性,您想从句子中搜索一个独立的词,则如果您搜索的单词存在于其他任何单词中,则解决方案-1也将返回true。例如,如果您在包含此单词** Beneficent**的句子中搜索cent,则解决方案-1将返回true。请记住,在您的正则表达式中添加空格。

String sentence = "In the Name of Allah, the Most Beneficent, the Most Merciful."
if (sentence.matches(".* cent .*")) {return true;}
else{return false;}

现在在Solution-2中,它将返回false,因为不存在独立的cent单词。

附加信息: 您可以根据需要在第二个解决方案中添加或删除任一侧的空格。


你确定这会起作用吗?看看Beneficent后面是逗号而不是空格。 - Joe C

1
   String sentence = "Check this answer and you can find the keyword with this code";
    String search = "keyword";

在给定的字符串中比较字符串行

if ((sentence.toLowerCase().trim()).equals(search.toLowerCase().trim())) {
System.out.println("not found");
}
else {  
    System.out.println("I found the keyword"); 
} 

看起来这与你在此处的其他答案大致相同。请不要重新发布; 相反,编辑您的旧答案以变得更好。它被投票降低可能是因为它是不正确的(尝试更改关键字,例如将其更改为“asdf”,并使代码报告找到它)。 - laalto

0
if (someString.indexOf("Hey")>=0) 
     doSomething();

0
尝试这段代码:
import java.util.Scanner;

public class wordContain {

    public static boolean wordCheck(String[] array, String word) {

        boolean check = false;

        for (int i = 0; i < array.length; i++) {
            if (array[i].equals(word)) {
                check = true;
                break;
            }
        }

        return check;
    }

    public static void main(String[] args) {
        // Getting the value from the Scanner
        Scanner scan = new Scanner(System.in);
        String sentence = scan.nextLine();
        String word = scan.nextLine().toLowerCase();

        // Split the sentence...
        String[] array = sentence.toLowerCase().split(" ");

        // pass the value to the wordCheck method
        boolean result = wordCheck(array, word);
        System.out.println(result);

        scan.close();
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接