如何在 Java 中解析字符串中的特定单词?

javaobject oriented programmingprogramming更新于 2024/2/14 13:32:17

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("搜索成功");
      } else {
         System.out.println("搜索不成功");
      }
   }
}

输出

搜索成功

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

相关文章


有用资源