29

Possible Duplicate:
How to see if a substring exists inside another string in Java 1.4

How would I search for a string in another string?

This is an example of what I'm talking about:

String word = "cat";
String text = "The cat is on the table";
Boolean found;

found = findInString(word, text); //this method is what I want to know

If the string "word" is in the string "text", the method "findInString(String, String)" returns true else it returns false.

Community
  • 1
  • 1
Meroelyth
  • 5,310
  • 9
  • 42
  • 52

5 Answers5

77

That is already in the String class:

String word = "cat";
String text = "The cat is on the table";
Boolean found;

found = text.contains(word);
Stephan
  • 4,395
  • 3
  • 26
  • 49
21

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;
}
Andy
  • 8,870
  • 1
  • 31
  • 39
4

word.contains(text)

Take a look at the JavaDocs.

Returns true if and only if this string contains the specified sequence of char values.

Marcelo
  • 4,580
  • 7
  • 29
  • 46
1

This can be done by using

boolean isContains = text.contains(word);
Chandra Sekhar
  • 18,914
  • 16
  • 84
  • 125
0

found = text.contains(word);

Juzer Ali
  • 4,109
  • 3
  • 35
  • 62