To check if string contains particular word

后端 未结 10 709
野的像风
野的像风 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条回答
  •  Happy的楠姐
    2020-12-08 05:21

    You can use regular expressions:

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

    .* -> 0 or more of any characters

    Hey -> The string you want

    If you will be checking this often, it is better to compile the regular expression in a Pattern object and reuse the Pattern instance to do the checking.

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

    Just note this will also match "Heyburg" for example since you didn't specify you're searching for "Hey" as an independent word. If you only want to match Hey as a word, you need to change the regex to .*\\bHey\\b.*

提交回复
热议问题