在Java中如何将字符串按多个空格分割

44

可能重复:
如何通过空格分割字符串

我需要在解析文本文件时帮助。 文本文件包含类似下面的数据:

This is     different type   of file.
Can not split  it    using ' '(white space)

我的问题是单词之间的空格不一致。有时只有一个空格,有时会出现多个空格。

我需要将字符串拆分,以便获得单词而不是空格。


1
不要重复,因为此问题是为了分割具有可变长度空格的文本。 - JGilmartin
我一点也不认为这是重复的问题。"可能的重复"没有解决多个空格的边角情况,而这恰恰是本问题的核心。作为参考,在搜索"java string split multiple spaces"时,该问题也是谷歌的首个结果。 - RvPr
7个回答

90

str.split("\\s+") 可以起到作用。正则表达式末尾的 +,将多个空格视为单个空格处理。它返回一个没有任何 " " 结果的字符串数组 (String[])。


26
您可以使用量词来指定您想要拆分的空格数量:-
    `+` - Represents 1 or more
    `*` - Represents 0 or more
    `?` - Represents 0 or 1
`{n,m}` - Represents n to m

因此,\\s+将会在 一个或多个 空格处拆分您的字符串

String[] words = yourString.split("\\s+");

此外,如果您想指定一些具体的数字,可以在{}之间给出您的范围:
yourString.split("\\s{3,6}"); // Split String on 3 to 6 spaces

7

使用正则表达式。

String[] words = str.split("\\s+");

5

您可以使用正则表达式模式

public static void main(String[] args)
{
    String s="This is     different type   of file.";
    String s1[]=s.split("[ ]+");
    for(int i=0;i<s1.length;i++)
    {
        System.out.println(s1[i]);
    }
}

输出

This
is
different
type
of
file.

你的解决方案只能按空格拆分,无法按其他空白字符(如\t\n\x0B\f\r)拆分。请改用字符类\s(任何空白字符),正如其他人所描述的那样。 String[] words = yourString.split("\\s+"); - jlordo

0
String spliter="\\s+";
String[] temp;
temp=mystring.split(spliter);

0

如果你不想使用分割方法,我可以给你另一种将字符串进行标记化的方法。以下是该方法:

public static void main(String args[]) throws Exception
{
    String str="This is     different type   of file.Can not split  it    using ' '(white space)";
    StringTokenizer st = new StringTokenizer(str, " "); 
    while(st.hasMoreElements())
    System.out.println(st.nextToken());
}
 }

他为什么不想使用split方法呢?毕竟它比StringTokenizer更好。请停止使用StringTokenizer。 - Rohit Jain
Rohit,你能否解释一下为什么split比StringTokenizer更好? - saurabh j
1
你可以查看以下链接:https://dev59.com/FXRB5IYBdhLWcg3wNk53、http://www.javamex.com/tutorials/regular_expressions/splitting_tokenisation_performance.shtml 和 https://dev59.com/12025IYBdhLWcg3wf2OE。 - Rohit Jain

0

你可以使用 String 类的 replaceAll(String regex, String replacement) 方法将多个空格替换为一个空格,然后再使用 split 方法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接