To check if string contains particular word

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

    Solution-1: - If you want to search for a combination of characters or an independent word from a sentence.

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

    Solution-2: - There is another possibility you want to search for an independent word from a sentence then Solution-1 will also return true if you searched a word exists in any other word. For example, If you will search cent from a sentence containing this word ** Beneficent** then Solution-1 will return true. For this remember to add space in your regular expression.

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

    Now in Solution-2 it wll return false because no independent cent word exist.

    Additional: You can add or remove space on either side in 2nd solution according to your requirements.

提交回复
热议问题