如何使用 java 分割以空格字符为分隔符的字符串?

javaobject oriented programmingprogramming更新于 2024/2/11 3:56:17

String 类的 split() 方法接受分隔符(以字符串的形式),根据分隔符将当前字符串分成较小的字符串,并将结果字符串作为数组返回。如果字符串不包含指定的分隔符,则此方法返回仅包含当前字符串的数组。

如果字符串不包含指定的分隔符,则此方法返回包含整个字符串作为元素的数组。

以空格作为分隔符分割字符串

要将字符串分割为以空格作为分隔符的字符串数组 −

  • 读取源字符串。

  • 通过传递 “ 来调用 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

相关文章


有用资源