【问题标题】:Split function increase new space character after splitting the string拆分功能在拆分字符串后增加新的空格字符
【发布时间】:2013-11-01 17:30:44
【问题描述】:

我在 java 中遇到了拆分函数的问题。我正在从文件中读取字符串列表并将它们存储到两个数组列表中。每个字符串包含一个字母 + 空格 + 数字。我使用 split 函数来获取其中一个数组列表中的字母和另一个数组列表中的数字。 numbers arraylist 正确添加数字,但是 letters arraylist 添加一个字母后跟空格,但我不知道为什么?!

这是文件:

a 1
b 01
c 001
d 000

代码:

Scanner s = new Scanner(new File("ListOfCodes.txt.txt"));
String output="";   
ArrayList<String> Codes =  new ArrayList<String>();
ArrayList<String>Letters = new ArrayList<String>();
String []separated ;
    while(s.hasNextLine())
    {
        output=s.nextLine();
           separated = output.split(" ");
          for(int k=0;k<separated.length;k++ )
          {   
              if(k==0)
             Letters.add(separated[k]);
              if(k==1)
              Codes.add(separated[k]);

          }
          output="";
    }
      output="";




      for(int i=0;i<Letters.size();i++)
        System.out.println(Letters.get(i));

      for(int i=0;i<Codes.size();i++)
          System.out.println(Codes.get(i));

代码数组列表的输出:

1
01
001
000

字母数组列表的输出:

a

b

c

d

【问题讨论】:

  • \r 或\n 等空格前后是否有换行符?如果是这样,可以试试split("\\s+")?
  • 我试过了,但没用:/
  • 那么我无法重现您的问题。我怀疑您使用的代码不同,或者输入文件的格式与您显示的不同。

标签: java regex string arraylist


【解决方案1】:

您的文件中可能有尾随空格。所以最好在将它们存储到列表之前使用trim 方法。

【讨论】:

  • 尾随空格或\r \n 符号
  • 是的,根据他的编辑,很明显他在那里得到了结尾字符。修剪将解决此问题。
【解决方案2】:

我建议像这样使用拆分:

separated = output.split("\\s+"); // \\s matches white spaces including newlines as well

这将为您提供最后带有条纹新行的字符串数组。

【讨论】:

    猜你喜欢
    • 2017-06-18
    • 2011-12-03
    • 2020-04-07
    • 1970-01-01
    • 2015-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多