将元素添加到字符串

时间:2017-12-12 23:44:27

标签: java

我使用java,我有以下字符串:

 points="335,234 285,320 185,320 135,234 186,147 285,147 335,233 ";

如何为每个数字添加2?...例如:

points="337,236 287,322 187,322 137,236 188,149 287,149 337,235 ";

1 个答案:

答案 0 :(得分:2)

您可以使用String#split获取数组中的所有单独数字,然后使用for进行迭代:

    String points = "335,234,285,320,185,320,135,234,186,147,285,147,335,233";
    String[] indvPoints = points.split(",");

    for(int i = 0; i < indvPoints.length; i++) {
        indvPoints[i] = String.valueOf(Integer.parseInt(indvPoints[i]) + 2);
    }

    points = Arrays.toString(indvPoints).replaceAll("[\\[\\] ]", "");
    System.out.println(points);

虽然我建议您先使用int数组,但它会更有效率并且不太可能遇到错误:

    int[] points = {335,234,285,320,185,320,135,234,186,147,285,147,335,233};

    for(int i = 0; i < points.length; i++) {
        points[i] += 2;
    }

    System.out.println(Arrays.toString(points));