我如何在另一个字符串中搜索字符串?
这是我所说的一个例子:
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
Run Code Online (Sandbox Code Playgroud)
如果字符串"word"在字符串"text"中,则方法"findInString(String,String)"返回true,否则返回false.
Ste*_*han 74
那已经在String类中了:
String word = "cat";
String text = "The cat is on the table";
Boolean found;
found = text.contains(word);
Run Code Online (Sandbox Code Playgroud)
And*_*ndy 16
使用该String.indexOf(String str)
方法.
来自JavaDoc:
返回指定子字符串第一次出现的字符串中的索引.
...
返回:如果字符串参数作为此对象中的子字符串出现,则返回第一个此类子字符串的第一个字符的索引; 如果它不作为子字符串出现,则返回-1.
所以:
boolean findInString(word, text)
{
return text.indexOf(word) > -1;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
171671 次 |
最近记录: |