如何将字符串拆分两次并自动创建一个表(包含n个元素)?

时间:2019-05-14 19:01:14

标签: java loops split

(这里是绝对的初学者) 我的目标是一张表格,其中一行中分隔数组中的元素由逗号分隔,并在空格(“”)后加新行。

必须在空格后开始新的一行(这意味着我不能用点代替它)。 我认为我最大的问题是我无法分开“漂亮105”(注意空格)。它始终被视为一个元素。

现在,字符串只有8个元素,但是您必须想象字符串很长。

首先,我想分割字符串(包括“ pretty 105”)

在循环中,我试图使其在“ pretty”之后“跳转”,因为它应该在此处拆分

public static void main(String[] args) {

    String str = "104,Jeans,B&B,pretty 105,Shoes,Nike,nice";
    List<String> Row = Arrays.asList(str.split(" "));
    List<String> List = Arrays.asList(str.split(","));      


    StringBuilder buf = new StringBuilder();
    buf.append("<html>" +
               "<body>" +
               "<table>" +
               "<tr>" +
               "<th>Number</th>" +
               "<th>Name</th>" +
               "<th>Maker</th>" +
               "<th>Description</th>" +
               "</tr>");

    for (int j = 0; j < Row.size(); j++) {

        int i = j*4;

        for (; i < List.size(); i++) {              

          if (i<1+i) {
              buf.append("<tr><td>")
              .append(List.get(i))
              .append("</td>");
          }
          else if (i>=1+i) {
              buf.append("<td>") 
              .append(List.get(i))
              .append("</td>");
          }
          else if (i>3+i) {
              buf.append("<td>") 
              .append(List.get(i))
              .append("</td></tr>");
              break;
          }
    }
    }



    buf.append("</table>" +
               "</body>" +
               "</html>");
    String html = buf.toString();
    System.out.println(buf);}

在此示例中,预期结果是:

编号 名称 制造商 说明

104,Jeans,B&B,漂亮
105,Shoes,Nike,nice

但是在上面的示例中,每个人都有自己的一行-除了“ pretty 105”:

104

牛仔裤

住宿加早餐旅馆

漂亮105

。 。

1 个答案:

答案 0 :(得分:0)

这就是你想要的吗?

public class Main {
    public static void main(String[] args) {
        String str = "104,Jeans,B&B,pretty 105,Shoes,Nike,nice";
        final String join = String.join("\n", str.split(" "));
        System.out.println(join);
    }
}

编辑:

public static void main(String[] args) {

    String str = "104,Jeans,B&B,pretty 105,Shoes,Nike,nice";
    final String[] lines = str.split(" ");

    StringBuilder buf = new StringBuilder();
    buf.append("<html>" + "<body>" + "<table>" + "<tr>" + "<th>Number</th>" + "<th>Name</th>" + "<th>Maker</th>" + "<th>Description</th>" + "</tr>");

    for (String line : lines) {
        buf.append("<tr><td>")
                .append(line)
                .append("</td><td>");
    }
    buf.append("</table>" + "</body>" + "</html>");
    System.out.println(buf);
}