如何在另一个字符串中搜索字符串?

可能重复:
如何查看Java 1.4中另一个字符串中是否存在子字符串

我如何在另一个字符串中搜索字符串?

这是我所说的一个例子:

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 

如果字符串“word”在字符串“text”中,则方法“findInString(String,String)”返回true,否则返回false。

那已经在String类中了:

 String word = "cat"; String text = "The cat is on the table"; Boolean found; found = text.contains(word); 

使用String.indexOf(String str)方法。

来自JavaDoc :

返回指定子字符串第一次出现的字符串中的索引。

返回:如果字符串参数作为此对象中的子字符串出现,则返回第一个此类子字符串的第一个字符的索引; 如果它不作为子字符串出现,则返回-1。

所以:

 boolean findInString(word, text) { return text.indexOf(word) > -1; } 

word.contains(text)

看看JavaDocs 。

当且仅当此字符串包含指定的char值序列时,才返回true。

这可以通过使用来完成

 boolean isContains = text.contains(word); 

found = text.contains(word);