【问题标题】:How to split the string into an array whose length is 10 in java? [duplicate]java中如何将字符串拆分为长度为10的数组? [复制]
【发布时间】:2013-02-06 08:52:24
【问题描述】:
5163583,601028,30,,0,"Leaflets, samples",Cycle 5 objectives,,20100804T071410,

如何将字符串变成长度为10的数组? 我预计数组是:

array[0]="5163583";
array[1]="601028";
array[2]="30";
array[3]="";
array[4]="0";
array[5]="Leaflets, samples";
array[6]="Cycle 5 objectives";
array[7]="";
array[8]="20100804T071410";
array[9]="";

非常感谢!

【问题讨论】:

  • 请以更易于理解的方式提出您的问题。上面那根长长的绳子是什么东西?
  • 遍历 java.lang.String 库类。解析字符串的方法有很多。oracle link
  • 按照你的逻辑,array[5]="Leaflets, samples"; 应该更接近于array[5]="\"Leaflets, samples\"";
  • 你已经拆分了。您只需要添加数组初始化。有什么问题?
  • @Bohemian:只有 bestsss 的答案似乎解决了引号内引号的转义问题。其他答案只是隐含假设引号永远不会出现在带引号的字符串中。

标签: java regex arrays string split


【解决方案1】:
String sb = "5163583,601028,30,,0,\"Leaflets, samples\",Cycle 5 objectives,,20100804T071410,";

String[] array = new String[10];
StringBuilder tmp = new StringBuilder();
int count=0;
for(int i=0, index=0; i<sb.length(); i++)
{
    char ch = sb.charAt(i);
    if(ch==',' && count==0)
    {
        array[index++] = tmp.toString();
        tmp = new StringBuilder();
        continue;
    }
    else if(ch=='"')
    {
        count = count==0 ? 1 : 0;
        continue;
    }

    tmp.append(ch);
}
for(String s : array)
    System.out.println(s);

【讨论】:

    【解决方案2】:

    您正在寻找 CSV 阅读器。你可以使用opencsv

    使用 opencsv 库:

    new CSVReader(new StringReader(inputString)).readNext()
    

    它返回一个列值数组。

    【讨论】:

      【解决方案3】:
      String string = 
          "5163583,601028,30,,0,\"Leaflets, samples\",Cycle 5 objectives,,20100804T071410,";
      
      Matcher m = Pattern.compile ("(\"[^\"]*\"|[^,\"]*)(?:,|$)").matcher (string);
      
      List <String> chunks = new ArrayList <String> ();
      while (m.find ())
      {
          String chunk = m.group (1);
          if (chunk.startsWith ("\"") && chunk.endsWith ("\""))
              chunk = chunk.substring (1, chunk.length () - 1);
          chunks.add (chunk);
      }
      
      String array [] = chunks.toArray (new String [chunks.size ()]);
      for (String s: array)
          System.out.println ("'" + s + "'");
      

      【讨论】:

      • 此解决方案的一个潜在问题是它假定引号从不出现在带引号的字符串中(未考虑引号的转义)。 (顺便问一下,为什么要在函数调用的参数前加一个空格?)。
      • @nhahtdh 这是一个问题,但缺少易于添加的功能。
      猜你喜欢
      • 1970-01-01
      • 2012-07-22
      • 1970-01-01
      • 2020-08-14
      • 1970-01-01
      • 2019-06-11
      • 2011-05-05
      • 2014-04-12
      相关资源
      最近更新 更多