如何在字符串中查找单词或子字符串
原文:https://www.studytonight.com/java-examples/how-to-find-a-word-or-substring-in-string
在这篇文章中,我们在字符串中找到一个单词或子字符串。字符串是一个字符序列和 Java 中的一个类。
为了在字符串中找到一个单词,我们使用了String
类的 indexOf()和 contains()方法。
indexOf()
方法用于查找当前字符串中指定子串的索引。如果找到的子串 else 返回-1,则返回一个正整数作为索引。
contains()
方法用于检查字符串是否包含指定的字符串。它返回真或假的布尔值。如果找到指定的字符串,则返回 true,否则返回 false。
举例时间:
让我们创建一个在字符串中查找单词的示例。这里,我们使用的是 indexOf()方法,该方法返回指定子字符串的索引。请看下面的例子。
public class Main {
public static void main(String[] args){
String str = "This sentance contains find me string";
System.out.println(str);
// find word in String
String find = "find me";
int i = str.indexOf(find);
if(i>0)
System.out.println(str.substring(i, i+find.length()));
else
System.out.println("string not found");
}
}
本标志包含“找到我”字符串 找到我
例 2
让我们创建另一个示例来查找字符串中的单词。这里,我们使用的是contains()
方法,如果找到指定的字符串,该方法返回 true。请看下面的例子。
public class Main {
public static void main(String[] args){
String str = "This sentance contains find me string";
System.out.println(str);
// find word in String
String find = "find me";
boolean val = str.contains(find);
if(val)
System.out.println("String found: "+find);
else
System.out.println("string not found");
}
}
本标志包含找到我字符串 找到的字符串:找到我