To check if string contains particular word

后端 未结 10 703
野的像风
野的像风 2020-12-08 04:55

So how do you check if a string has a particular word in it?

So this is my code:

a.setOnClickListener(new View.OnClickListener() {

        @Overri         


        
相关标签:
10条回答
  • 2020-12-08 05:24

    Maybe this post is old, but I came across it and used the "wrong" usage. The best way to find a keyword is using .contains, example:

    if ( d.contains("hello")) {
                System.out.println("I found the keyword");
    }
    
    0 讨论(0)
  • 2020-12-08 05:26

    Not as complicated as they say, check this you will not regret.

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

    You can change the toLowerCase() if you want.

    0 讨论(0)
  • 2020-12-08 05:29

    The other answer (to date) appear to check for substrings rather than words. Major difference.

    With the help of this article, I have created this simple method:

    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();
    }
    
    0 讨论(0)
  • 2020-12-08 05:32

    .contains() is perfectly valid and a good way to check.

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

    Since you didn't post the error, I guess d is either null or you are getting the "Cannot refer to a non-final variable inside an inner class defined in a different method" error.

    To make sure it's not null, first check for null in the if statement. If it's the other error, make sure d is declared as final or is a member variable of your class. Ditto for c.

    0 讨论(0)
提交回复
热议问题