So how do you check if a string has a particular word in it?
So this is my code:
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!"); } } });
I'm getting an error.
The simplest way to check if a string contains a substring in Python is to use the in operator. This will return True or False depending on whether the substring is found. For example: sentence = 'There are more trees on Earth than stars in the Milky Way galaxy' word = 'galaxy' if word in sentence: print('Word found.
Definition and Usage. The includes() method returns true if a string contains a specified string. Otherwise it returns false .
You can use contains(), indexOf() and lastIndexOf() method to check if one String contains another String in Java or not. If a String contains another String then it's known as a substring. The indexOf() method accepts a String and returns the starting position of the string if it exists, otherwise, it will return -1.
Use the String. includes() method to check if a string contains a character, e.g. if (str. includes(char)) {} . The include() method will return true if the string contains the provided character, otherwise false is returned.
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.
.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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With