【问题标题】:Convert a String (formatted just like an ArrayList<String>) to an actual ArrayList<String>将字符串(格式类似于 ArrayList<String>)转换为实际的 ArrayList<String>
【发布时间】:2011-03-28 15:45:10
【问题描述】:

我正在尝试将字符串转换为 ArrayList。例如,我的 Struts2 webapp 以类似于下面的格式返回这个名为 row 的字符串:

[A, BB, CCC, DDDD, 1, 0, 1](类似的东西)

我需要将它们转换成一个 ArrayList,这样我就可以在另一个 JSP 页面中预填充一些表单。我硬编码了一种将此类字符串转换为列表形式的方法:

        StringBuffer rowBuffer = new StringBuffer(row);
        int startIndex = 0;
        int endIndex = rowBuffer.indexOf(",") - 1;
        rowBuffer.deleteCharAt(rowBuffer.indexOf("["));
        rowBuffer.deleteCharAt(rowBuffer.indexOf("]"));
        while(startIndex != -1 && endIndex != -1 && startIndex < endIndex)
        {
          String subString = rowBuffer.substring(startIndex, endIndex);

       if(subString.contains(","))
       {
          rowList.add(" ");
          startIndex = endIndex + 1;
          endIndex = rowBuffer.indexOf(",", startIndex);
       }

       else
       {
        rowList.add(subString);
        startIndex = endIndex + 2;
        endIndex = rowBuffer.indexOf(",", startIndex + 1);
       }

       if(endIndex == -1)
       {
          rowList.add(rowBuffer.substring(startIndex));
          break;
       }
    }

这适用于所有字段都已填充的情况。但是,假设我有一个看起来像这样的字符串: [A, BB, , , 1, 0, 0] (缺少第 3 和第 4 个字段),然后我得到一些不起作用的东西(空白元素不'没有正确注册,并且列表的大小是6,当它应该是7)。有比硬编码更优雅的解决方案吗?如果没有,有人可以为我指出如何处理带有空白字段的案例的正确方向吗?谢谢!

【问题讨论】:

  • 让我们退后一步:为什么您的 Struts2 webapp 会以这种格式返回这些值?如果它将每个值作为单独的参数返回,对我来说会更有意义。 List 是否在隐藏的输入字段中被简单地打印出来,目的是在后续请求中保留它?然后,您可以只打印多个名称相同但值不同的隐藏字段。这在 HTML/HTTP 中完全有效。我不使用 Struts2,但 Servlet API 会将其返回为 String[] by request.getParameterValues()
  • 没关系,我弄明白了(有一些更硬的编码)。我正在使用隐藏字段,但无论如何我都不是 HTML / JSP / Struts2 / web 编程专家,所以我不想更改我的所有代码并最终得到一些最终无法正常工作的东西。不过谢谢!
  • 无论如何,这个项目祝你好运。我发现了您关于表格中按钮的另一个 Struts2 问题。使用纯 HTML/JSP/Servlet 或使用 JSF(Java EE 提供的 Struts2 的竞争对手)非常容易。但是,我不做Struts2,所以无法回答。 Stackoverflow 也没有太多的 Struts2 专家。在 Struts2 邮件列表中,您可能会有更好的运气。尽量不要摆弄黑客和讨厌的解决方法,而不是简单、干净和正确的解决方案。从长远来看,这只会造成更大的伤害。

标签: java string struts2 arraylist


【解决方案1】:

请试试这个:

import java.util.regex.*;

// ...

// Working code    
rowBuffer.deleteCharAt(rowBuffer.indexOf("["));
rowBuffer.deleteCharAt(rowBuffer.indexOf("]"));
// Create a pattern to match breaks
Pattern p = Pattern.compile("\\s*,\\s*");
// Split input with the pattern
String[] result = p.split(rowBuffer);
rowList = new ArrayList(Arrays.asList(result)); 

注意:这预先假定字符串本身不包含逗号并且不被引用。如果您想在字段和引用值中使用逗号解析真正的 CSV,请不要使用正则表达式和拆分;而是使用专用的状态机 CSV 解析器(这是一个示例:http://opencsv.sourceforge.net/ - 或者您可以自己滚动,例如 BalusC example here

【讨论】:

  • 嗨 DVK,在某些情况下,我在字符串之间有空格(例如:[AAA, BB BBB, CCC, DDDD, 1, 0, 1]),但我想得到“BB BBB” ,而不是“BB”和“BBB”。我还不太懂正则表达式……你能帮帮我吗?
  • 在我看来@DVK 的代码在逗号分隔符前后处理空格... --JA
  • @Raymond Chang - \s*,\s* 表示匹配左右两边由可选空格包围的逗号。正是您需要的。
  • @DVK:你写了compile("[\\s*,\\s*]+");您误解了字符类 [...] 的工作原理。这将匹配星号。
  • 如果字符串本身包含commas 怎么办? ://
【解决方案2】:

好吧,我稍微更改了我的代码并使其工作(它可能远非最优雅的解决方案,但它对我有用......

    StringBuffer rowBuffer = new StringBuffer(row);
    int startIndex = 0;
    int endIndex = rowBuffer.indexOf(",") - 1;
    rowBuffer.deleteCharAt(rowBuffer.indexOf("["));
    rowBuffer.deleteCharAt(rowBuffer.indexOf("]"));
    while(startIndex != -1 && endIndex != -1 && startIndex < endIndex)
    {
      String subString = rowBuffer.substring(startIndex, endIndex);

       if(subString.contains(","))
       {
          rowList.add(" ");
          startIndex = endIndex - 1;
          endIndex = rowBuffer.indexOf(", ", startIndex + 1);
       }

       else
       {
         if(subString.equals("1"))
             rowList.add("True");
         else if(subString.equals("0"))
             rowList.add("False");
         else
          rowList.add(subString);
        startIndex = endIndex + 2;
        endIndex = rowBuffer.indexOf(",", startIndex + 1);
       }

       if(endIndex == -1)
       {
          if(subString.equals("1"))
             rowList.add("True");
          else if(subString.equals("0"))
             rowList.add("False");
          break;
       }
    }

【讨论】:

    【解决方案3】:

    假设格式是AbstractCollection.toString()指定的,那么你可以简单地:

    • 删除周围的括号(使用简单的substring
    • 然后split ", "(逗号和空格)
    • 使用Arrays.asListString[] 包装成List&lt;String&gt;
      • 如有必要,使用它来填充ArrayList&lt;String&gt;

    请注意,如果元素本身可以包含", ",这将中断。为此,该字符串必须是一个分隔符,而不是实际标记的一部分。

    这里有一个 sn-p 来说明:

        String s = "[A, BB, CCC, DDDD, 1, 0, 1]";
        String[] parts = s.substring(1, s.length() - 1).split(", ");
        List<String> list = new ArrayList(Arrays.asList(parts));
    
        for (String part : list) {
            System.out.print("{" + part + "} ");
        } // {A} {BB} {CCC} {DDDD} {1} {0} {1} 
    

    【讨论】:

      猜你喜欢
      • 2014-05-16
      • 2011-08-20
      • 1970-01-01
      • 1970-01-01
      • 2012-08-31
      • 1970-01-01
      • 2013-11-19
      • 2021-07-12
      • 2023-03-06
      相关资源
      最近更新 更多