如何在Java中使用句子作為分隔符分割字串?


String 類的 split() 方法接受一個表示分隔符的字串值,並將其分割成一個標記(單詞)陣列,將兩個分隔符之間出現的字串視為一個標記。

例如,如果您將單個空格“ ”作為分隔符傳遞給此方法並嘗試分割一個字串。此方法將兩個空格之間的單詞視為一個標記,並返回當前字串中單詞(空格之間)的陣列。

如果字串不包含指定的分隔符,則此方法將返回一個包含整個字串作為元素的陣列。

示例

 即時演示

public class SplitExample {
   public static void main(String[] args) {
      String str = "Hi how are you welcome to Tutorialspoint";
      String words[] = str.split(" ");
      for(String token : words) {
         System.out.println(token);
      }
   }
}

輸出

Hi
how
are
you
welcome
to
Tutorialspoint

使用句子作為分隔符分割字串

如果您將句子作為分隔符傳遞,您也可以分割句子,如果這樣做,則每次出現指定句子時,字串都會被分割為一個單獨的標記。

示例

以下 Java 程式將檔案內容讀入一個字串,並使用帶句子作為分隔符的 split() 方法將其分割。

public class StringOccurrence {
   public static String fileToString(String filePath){
      Scanner sc = null;
      String input = null;
      StringBuffer sb = null;
      try {
         sc = new Scanner(new File(filePath));
         sb = new StringBuffer();
         while (sc.hasNextLine()) {
            input = sc.nextLine();
            sb.append(" "+input);
         }
      }
      catch(Exception ex) {
         ex.toString();
      }
      return sb.toString();
   }
   public static void main(String args[]) throws FileNotFoundException {
      String filePath = "D://sampleData.txt";
      String text = fileToString(filePath);
      String array[] = text.split("We don’t force our readers to sign up with us or submit their details either");
      for(String token : array) {
         System.out.println(" ");
         System.out.println(token);
      }
   }
}

輸出

Tutorials Point originated from the idea that there exists a class of readers 
who respond better to online content and prefer to learn new skills at their 
own pace from the comforts of their drawing rooms. The journey commenced with 
a single tutorial on HTML in 2006 and elated by the response it generated, 
we worked our way to adding fresh tutorials to our repository which now 
proudly flaunts a wealth of tutorials and allied articles on topics ranging 
from programming languages to web designing to academics and much more. 
40 million readers read 100 million pages every month. Our content and 
resources are freely available and we prefer to keep it that way to 
encourage our readers acquire as many skills as they would like to.
No preconditions and no impediments. Simply Easy Learning!

更新於: 2019年9月10日

11K+ 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.