在java中的多个空格上拆分字符串

Sac*_*tre 21 java string split

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

解析文本文件时我需要帮助.文本文件包含数据

This is     different type   of file.
Can not split  it    using ' '(white space)
Run Code Online (Sandbox Code Playgroud)

我的问题是单词之间的空格不相似.有时会有单个空间,有时会给出多个空格.

我需要以这样的方式分割字符串,即我只能获得单词,而不是空格.

Bhe*_*ung 45

试试看str.split("\\s+").它返回一个字符串数组(+).


Roh*_*ain 15

您可以使用它Quantifiers来指定要拆分的空格数: -

    `+` - Represents 1 or more
    `*` - Represents 0 or more
    `?` - Represents 0 or 1
`{n,m}` - Represents n to m
Run Code Online (Sandbox Code Playgroud)

因此,\\s+将在one or more空格上分割您的字符串

String[] words = yourString.split("\\s+");
Run Code Online (Sandbox Code Playgroud)

此外,如果您想指定一些特定的数字,您可以在以下两者之间给出您的范围{}:

yourString.split("\\s{3,6}"); // Split String on 3 to 6 spaces
Run Code Online (Sandbox Code Playgroud)


ale*_*lex 6

使用正则表达式。

String[] words = str.split("\\s+");
Run Code Online (Sandbox Code Playgroud)


Bha*_*hah 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]);
    }
}
Run Code Online (Sandbox Code Playgroud)

产量

This
is
different
type
of
file.
Run Code Online (Sandbox Code Playgroud)