使用StringBuilder时从上一个中删除了逗号

时间:2016-01-12 09:54:30

标签: java stringbuilder stringbuffer

我有以下Java程序,我不希望在我的最后一个元素之后分配“,”该怎么办?

String range = "400-450";
        Integer startRange = null;
        Integer endRange = null;
        StringTokenizer st = new StringTokenizer(range,"-");  
        while(st.hasMoreTokens()) { 
            startRange = Integer.parseInt(st.nextToken()); 
            endRange= Integer.parseInt(st.nextToken()); 
        } 
        StringBuilder sb = new StringBuilder();
        for (int i = startRange; i <= endRange; i++) {
            sb.append(i).append(",");
        }
        System.out.println(sb);

输出应该是 400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426,427,428,429,430,431,432,433,434,435,436,437,438,439,440,441,442,443,444,445,446,447,448,449,450 - &gt;最后没有逗号

6 个答案:

答案 0 :(得分:1)

对于 Java 8 ,您可以切换到新类StringJoiner,该类已为正好用于添加了:

    StringJoiner sb = new StringJoiner(",");
    for (int i = startRange; i <= endRange; i++) {
        sb.add(String.valueOf(i));
    }
    System.out.println(sb.toString());

手动执行,我建议在项目之前添加逗号,然后使用substring(1):

    for (int i = startRange; i <= endRange; i++) {
        sb.append(",").append(i);
    }
    //Check for empty before!
    System.out.println(sb.substring(1));

答案 1 :(得分:1)

正如@Jan所说,如果你有Java8,请使用StringJoiner。否则,您可以在新条目之前添加分隔符,并通过将分隔符初始化为空白来区别对待第一个项目。

   String separator = "";
    for (int i = startRange; i <= endRange; i++) {
        sb.append(separator).append(i);
        separator = ",";
    }

这是Java8版本

    StringJoiner sb = new StringJoiner(",");
    for (int i = startRange; i <= endRange; i++) {
        sb.add(String.valueOf(i));
    }

答案 2 :(得分:0)

在最后一个元素到达之前,让最后一个附加逗号的循环停止:

String range = "400-450";
        Integer startRange = null;
        Integer endRange = null;
        StringTokenizer st = new StringTokenizer(range,"-");  
        while(st.hasMoreTokens()) { 
            startRange = Integer.parseInt(st.nextToken()); 
            endRange= Integer.parseInt(st.nextToken()); 
        } 
        StringBuilder sb = new StringBuilder();
        // here, the "<=" was changed to "<"
        for (int i = startRange; i < endRange; i++) {
            sb.append(i).append(",");
        }
        // append last element
        sb.append(endrange)
        System.out.println(sb);

答案 3 :(得分:0)

您在每个","后追加i 只有在您没有到达endRange

时才尝试附加","

做的:

for (int i = startRange; i <= endRange; i++) {
            sb.append(i)
            if (i != endRange)
              sb.append(",");
        }

这种方式","不会在最后一个号码后添加到sb。

答案 4 :(得分:0)

将Joiner(guava)用于Java&lt; 8。

List<Integer> numbers = Lists.newArrayList(1, 3, 4, 5, 23);
System.out.println(Joiner.on(",").join(numbers));

输出是:

1,3,4,5,23

答案 5 :(得分:0)

就像

一样简单
for (int i = startRange; i <= endRange; i++) {
   sb.append(i);
   if(i != endRange)
        sb.append(",");
}