String类的split()方法接受一个定界符(以字符串的形式),基于该定界符将当前String分成较小的字符串,并将所得的字符串作为数组返回。如果String不包含指定的定界符,则此方法返回仅包含当前字符串的数组。
如果String不包含指定的分隔符,则此方法返回一个包含整个字符串作为元素的数组。
要将字符串拆分为以白色节奏作为分隔符的字符串数组-
读取源字符串。
通过传递“”作为定界符来调用split()方法。
打印结果数组。
以下Java程序将文件的内容读取到Sting中,并使用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(" ");
      for(int i = 0; i < result.length; i++) {
         System.out.println(result[i]);
      }
   }
}Hello how are you