如何在 Java 中解析字符串以查找特定单词?
Java 中有各种方法可以用来解析字符串以查找特定单词。这里我们将讨论其中 3 种。
contains() 方法
String 类的 contains() 方法接受一个字符序列值,并验证它是否存在于当前字符串中。如果找到,则返回 true,否则返回 false。
示例
import java.util.StringTokenizer;
import java.util.regex.Pattern;
public class ParsingForSpecificWord {
public static void main(String args[]) {
String str1 = "Hello how are you, welcome to Tutorialspoint";
String str2 = "Tutorialspoint";
if (str1.contains(str2)){
System.out.println("Search successful");
} else {
System.out.println("Search not successful");
}
}
}输出
Search successful
indexOf() 方法
String 类的 indexOf() 方法接受一个字符串值,并在当前字符串中查找其(起始)索引并返回它。如果在当前字符串中找不到给定字符串,则此方法返回 -1。
示例
public class ParsingForSpecificWord {
public static void main(String args[]) {
String str1 = "Hello how are you, welcome to Tutorialspoint";
String str2 = "Tutorialspoint";
int index = str1.indexOf(str2);
if (index>0){
System.out.println("Search successful");
System.out.println("Index of the word is: "+index);
} else {
System.out.println("Search not successful");
}
}
}输出
Search successful Index of the word is: 30
StringTokenizer 类
使用 StringTokenizer 类,您可以根据分隔符将字符串划分为较小的标记,并遍历它们。以下示例将源字符串中的所有单词标记化,并使用 **equals()** 方法将每个单词与给定单词进行比较。
示例
import java.util.StringTokenizer;
public class ParsingForSpecificWord {
public static void main(String args[]) {
String str1 = "Hello how are you welcome to Tutorialspoint";
String str2 = "Tutorialspoint";
//Instantiating the StringTookenizer class
StringTokenizer tokenizer = new StringTokenizer(str1," ");
int flag = 0;
while (tokenizer.hasMoreElements()) {
String token = tokenizer.nextToken();
if (token.equals(str2)){
flag = 1;
} else {
flag = 0;
}
}
if(flag==1)
System.out.println("Search successful");
else
System.out.println("Search not successful");
}
}输出
Search successful
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP