如何在 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

更新於: 2019年10月11日

729 次檢視

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.