如何在Java中根據固定字元序列分割字串?


String類的**split()**方法接受一個分隔符(字串形式),根據分隔符將當前字串分割成更小的字串,並將結果字串作為陣列返回。如果字串不包含指定的分隔符,則此方法返回只包含當前字串的陣列。

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

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

根據固定字元序列分割字串

每次出現特定字串時,將字串分割成字串陣列:

  • 讀取源字串。

  • 透過傳遞所需的字串作為分隔符來呼叫**split()**方法。

  • 列印結果陣列。

示例

下面的Java程式將檔案內容讀取到一個字串中,並使用split()方法和另一個字串作為分隔符來分割它。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class SplitExample {
   public static void main(String args[]) throws FileNotFoundException {
      Scanner sc = new Scanner(new File("D:\sample.txt"));
      StringBuffer sb = new StringBuffer();
      String input = new String();
      while (sc.hasNextLine()) {
         input = sc.nextLine();
         sb.append(input);
      }
      String source = sb.toString();
      String result[] = source.split(" to ");
      System.out.print(Arrays.toString(result));
   }
}

輸出

[Tutorials Point originated from the idea that there exists a class of readers who respond better,
on-line content and prefer, learn new skills at their own pace from the comforts of their drawing rooms.]

更新於:2019年10月10日

534 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.