How to search a string in another string? [duplicate]
Solution 1:
That is already in the String class:
String word = "cat";
String text = "The cat is on the table";
Boolean found;
found = text.contains(word);
Solution 2:
Use the String.indexOf(String str)
method.
From the JavaDoc:
Returns the index within this string of the first occurrence of the specified substring.
...
Returns: if the string argument occurs as a substring within this object, then the index of the first character of the first such substring is returned; if it does not occur as a substring, -1 is returned.
So:
boolean findInString(word, text)
{
return text.indexOf(word) > -1;
}
Solution 3:
word.contains(text)
Take a look at the JavaDocs.
Returns true if and only if this string contains the specified sequence of char values.
Solution 4:
This can be done by using
boolean isContains = text.contains(word);