for循环迭代-如何避免逗号

时间:2018-07-04 09:18:01

标签: java

我想将字符串与“,”一起从2到6。当我执行以下代码时,我得到了输出,但输出以逗号开头。如何避免这种情况??

float dp = px/dpi;

输出:

    String name="";
    String s = "1,two,three,four,five,six,seven"; //this is a sample string, original string might contain more words separated by ","
    String[] split = s.split(",");
    System.out.println("Splitted Length: " +split.length);
    if(split.length>2) {
        for(int i=1; i<split.length-1;i++) {
            name = name+","+split[i];
        }
    }
    System.out.println(name);

如何避免出现第一个逗号。

7 个答案:

答案 0 :(得分:5)

请停止使用for循环。不要发明新事物。了解API。

List<String> valuesList = Arrays.asList(array).subList(x, y);
String newValuesString = String.join(",", valuesList);

答案 1 :(得分:3)

您可以为此使用Java8 StreamPattern

String result = Pattern.compile(",").splitAsStream(s)
    .skip(1)
    .collect(Collectors.joining(","));

答案 2 :(得分:2)

您可以通过以下方式重写代码:

 if(split.length>2) {
        name = split[1];
        for(int i=2; i<split.length-1;i++) {
            name = name+","+split[i];
        }

答案 3 :(得分:1)

在循环外添加第一个元素:

if(split.length>2) {
    name = split[0];
    for(int i=1; i<split.length-1;i++) {
        name = name+","+split[i];
    }
}

这还包括第一个元素("1"),您出于某种原因决定在结果中省略

答案 4 :(得分:0)

您可以尝试这个,

  String name = "";
        String s = "1,two,three,four,five,six,seven"; 
        String[] split = s.split(",");
        System.out.println("Splitted Length: " + split.length);
        if (split.length > 2) {
            for (int i = 1; i < split.length - 1; i++) {
                if (name.isEmpty()) {
                    name = split[i];
                } else {
                    name = name + "," + split[i];
                }

            }
        }
        System.out.println(name);
    }

答案 5 :(得分:0)

尝试以下代码

String name="";
String s = "1,two,three,four,five,six,seven"; //this is a sample string, original string might contain more words separated by ","
String[] split = s.split(",");
System.out.println("Splitted Length: " +split.length);
if(split.length>2) {
    for(int i=1; i<split.length-1;i++) {
      if (i=1)            
        {name = name+split[i];}
      else 
        {name=name+","+split[i];}
    }
}
System.out.println(name);

EXPLANATION:-在此代码中,for循环仅在for循环的第一个插入处使用了一个不同的(name = name + split [i];)方程,这有助于避免第一个“,”

答案 6 :(得分:0)

将定界符存储在变量中,并在第一次迭代后对其进行更新:

String delim = "";
for(int i=1; i<split.length-1;i++) {
    name = name+delim+split[i];
    delim = ",";
}

但是,使用indexOflastIndexOf直接在字符串中查找第一个和最后一个逗号会更容易:

int first = s.indexOf(',');
int last = s.lastIndexOf(',');
if (first != last) {
    name = s.substring(first + 1, last);
}