【问题标题】:Splitting string on multiple spaces in java [duplicate]在java中的多个空格上拆分字符串[重复]
【发布时间】:2012-10-16 09:36:36
【问题描述】:

可能重复:
How to split a String by space

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

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

我的问题是单词之间的空格不相似。有时是一个空格,有时是多个空格。

我需要以这样一种方式拆分字符串,以便只得到单词,而不是空格。

【问题讨论】:

  • 不重复,因为这个问题是用可变长度的空格分割
  • 我看不出这是怎么复制的。 “可能的重复”没有解决多空格的极端情况,这是问题的重点。供参考,这个问题也是google上搜索java string split multiple spaces时的第一个结果

标签: java string split


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

        `+` - Represents 1 or more
        `*` - Represents 0 or more
        `?` - Represents 0 or 1
    `{n,m}` - Represents n to m
    

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

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

    另外,如果你想指定一些具体的数字,你可以在{}之间给出你的范围:

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

    【讨论】:

      【解决方案3】:

      使用正则表达式。

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

      【讨论】:

        【解决方案4】:

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

        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+");
        【解决方案5】:

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

        【讨论】:

          【解决方案6】:
          String spliter="\\s+";
          String[] temp;
          temp=mystring.split(spliter);
          

          【讨论】:

            【解决方案7】:

            如果你不想使用 split 方法,我给你另一种方法来标记你的字符串。这里是方法

            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());
            }
             }
            

            【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2017-12-10
            • 2011-12-28
            • 2012-11-09
            • 1970-01-01
            • 2020-04-17
            • 1970-01-01
            相关资源
            最近更新 更多