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

时间:2012-02-14 11:28:18

标签: java string

  

可能重复:
  How to see if a substring exists inside another string in 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。

5 个答案:

答案 0 :(得分:72)

那已经在String类中了:

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

found = text.contains(word);

答案 1 :(得分:16)

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

来自JavaDoc

  

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

     

...

     

返回:如果字符串参数作为其中的子字符串出现   对象,然后是第一个这样的第一个字符的索引   返回substring;如果它不作为子字符串出现,则为-1   返回。

所以:

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

答案 2 :(得分:4)

word.contains(text)

查看JavaDocs

  

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

答案 3 :(得分:1)

这可以通过

来完成
boolean isContains = text.contains(word);

答案 4 :(得分:0)

found = text.contains(word);