gpt4 book ai didi

java - 使用 StringBuilder 时从 last 中删除逗号

转载 作者:行者123 更新时间:2023-11-30 08:05:53 28 4
gpt4 key购买 nike

我有以下 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 --> without comma at last

最佳答案

对于 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));

关于java - 使用 StringBuilder 时从 last 中删除逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34740362/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com