Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To check if string contains particular word

Tags:

java

android

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.

like image 606
WhiplashOne Avatar asked Jun 16 '13 15:06

WhiplashOne


People also ask

How do you check if a string contains a particular word in Python?

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.

How do you check if a string contains a particular word in JavaScript?

Definition and Usage. The includes() method returns true if a string contains a specified string. Otherwise it returns false .

How do I check if a string contains text?

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.

How do I check if a string contains a specific character?

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.


2 Answers

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.

like image 168
Farukest Avatar answered Sep 29 '22 18:09

Farukest


.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.

like image 39
Ken Wolf Avatar answered Sep 29 '22 17:09

Ken Wolf