To check if string contains particular word

后端 未结 10 734
野的像风
野的像风 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:11

    It's been correctly pointed out above that finding a given word in a sentence is not the same as finding the charsequence, and can be done as follows if you don't want to mess around with regular expressions.

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

    Output:

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

    P.S Make sure you have filtered out any commas or full stops beforehand.

提交回复
热议问题