Java - 格式化ArrayList中的字符串

时间:2014-09-05 07:28:04

标签: java arraylist formatting

我有一个ArrayList,其中包含以下格式的元素:

1. 11111 "Top Secret Twenty One - Janet Evanovich" $8.99 1 0% $8.99

格式化ArrayList中每个元素的最佳方法是使其看起来如下:

11111, "Top Secret Twenty One - Janet Evanovich", 8.99, 1, 0.0, 8.99

我基本上遍历ArrayList并将其放在输出文件中。如何在此循环中对其进行格式化?

BufferedWriter bw = new BufferedWriter(file);

for(int i = 0; i<items.size(); i++){

    bw.append(items.get(i).toString());
}

2 个答案:

答案 0 :(得分:0)

您应该在列表中使用POJO。如果你必须这样做,我希望这可以帮助你:

        String s1 = "1. 11111 \"Top Secret Twenty One - Janet Evanovich\" $8.99 1 0% $8.99";
        String first = s1.substring(3);
        first = first.substring(0, first.indexOf(" "));
        String title = s1.substring(s1.indexOf("\""), s1.lastIndexOf("\"")+1);
        String rest = s1.substring(s1.lastIndexOf("\"")).replaceAll("\\$", "").replaceAll("%", "");
        String result = first+" ,"+title+rest.replaceAll(" ", ", ");

答案 1 :(得分:0)

为什么不使用正则表达式?

    Pattern compile = Pattern.compile("\\d+\\.\\s(\\d+)\\s\\\"(.+)\\\"\\s\\$(\\d+\\.\\d+)\\s(\\d+)\\s(\\d+)%\\s\\$(\\d+\\.\\d+)");
    Matcher matcher = compile.matcher("1. 11111 \"Top Secret Twenty One - Janet Evanovich\" $8.99 1 0% $8.99");
    if(matcher.find()){
        String[] tab = {matcher.group(1), '\"'+matcher.group(2)+'\"', matcher.group(3), matcher.group(4), ""+(Double.parseDouble(matcher.group(5))/100), matcher.group(6)};
        System.out.println(String.join(", ",tab));
    }