When you have to loop through a collection and make a string of each data separated by a delimiter, you always end up with an extra delimiter at the end, e.g.
当您需要循环一个集合,并将每个数据用分隔符分隔成一个字符串时,您最后总会得到一个额外的分隔符,例如。
for(String serverId : serverIds) {
sb.append(serverId);
sb.append(",");
}
Gives something like : serverId_1, serverId_2, serverId_3,
给出如下内容:serverId_1, serverId_2, serverId_3,
I would like to delete the last character in the StringBuilder (without converting it because I still need it after this loop).
我想删除StringBuilder中的最后一个字符(不需要转换它,因为在这个循环之后我仍然需要它)。
16 个解决方案
#1
494
Others have pointed out the deleteCharAt
method, but here's another alternative approach:
其他人指出了deleteCharAt方法,但这里有另一种方法:
String prefix = "";
for (String serverId : serverIds) {
sb.append(prefix);
prefix = ",";
sb.append(serverId);
}
Alternatively, use the Joiner
class from Guava :)
或者,使用Guava的Joiner类:)
As of Java 8, StringJoiner
is part of the standard JRE.
在Java 8中,StringJoiner是标准JRE的一部分。
#2
306
Another simple solution is:
另一个简单的解决方案是:
sb.setLength(sb.length() - 1);
A more complicated solution:
一个更复杂的解决方案:
The above solution assumes that sb.length() > 0
... i.e. there is a "last character" to remove. If you can't make that assumption, and/or you can't deal with the exception that would ensue if the assumption is incorrect, then check the StringBuilder's length first; e.g.
上述解决方案假设sb.length() >…也就是说,有一个“最后一个字符”要删除。如果你不能做那个假设,或者你不能处理一个例外,如果这个假设是错误的,那么首先检查StringBuilder的长度;如。
// Readable version
if (sb.length() > 0) {
sb.setLength(sb.length() - 1);
}
or
或
// Concise but harder-to-read version of the above.
sb.setLength(Math.max(sb.length() - 1, 0));
#3
122
sb.deleteCharAt(sb.length() - 1)
#4
48
As of Java 8, the String class has a static method join
. The first argument is a string that you want between each pair of strings, and the second is an Iterable<CharSequence>
(which are both interfaces, so something like List<String>
works. So you can just do this:
在Java 8中,String类有一个静态方法连接。第一个参数是在每一对字符串之间想要的字符串,第二个参数是一个Iterable
String.join(",", serverIds);
Also in Java 8, you could use the new StringJoiner
class, for scenarios where you want to start constructing the string before you have the full list of elements to put in it.
在Java 8中,您也可以使用新的StringJoiner类,在您想要开始构建字符串的场景中,您需要在将完整的元素列表放入其中之前开始构建字符串。
#5
33
In this case,
在这种情况下,
sb.setLength(sb.length() - 1);
is preferable as it just assign the last value to '\0'
whereas deleting last character does System.arraycopy
因为它只将最后一个值赋值为'\0',而删除最后一个字符是System.arraycopy
#6
24
Just get the position of the last character occurrence.
得到最后一个字符出现的位置。
for(String serverId : serverIds) {
sb.append(serverId);
sb.append(",");
}
sb.deleteCharAt(sb.lastIndexOf(","));
Since lastIndexOf
will perform a reverse search, and you know that it will find at the first try, performance won't be an issue here.
由于lastIndexOf将执行反向搜索,而且您知道它将在第一次尝试中发现,性能在这里不会成为问题。
#7
10
Another alternative
另一种替代方法
for(String serverId : serverIds) {
sb.append(",");
sb.append(serverId);
}
sb.deleteCharAt(0);
#8
10
With Java-8
you can use static method of String
class,
使用Java-8可以使用String类的静态方法,
String#join(CharSequence delimiter,Iterable<? extends CharSequence> elements)
.
字符串#加入(CharSequence进行分隔符,Iterable < ?扩展CharSequence进行>元素)。
public class Test {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("James");
names.add("Harry");
names.add("Roy");
System.out.println(String.join(",", names));
}
}
OUTPUT
输出
James,Harry,Roy
#9
6
Alternatively,
另外,
StringBuilder result = new StringBuilder();
for(String string : collection) {
result.append(string);
result.append(",");
}
return result.substring(0, result.length() - 1) ;
#10
5
StringBuilder sb = new StringBuilder();
sb.append("abcdef");
sb.deleteCharAt(sb.length() - 1);
assertEquals("abcde",sb.toString());
// true
#11
3
Yet another alternative:
另一个选择:
public String join(Collection<String> collection, String seperator) {
if (collection.isEmpty()) return "";
Iterator<String> iter = collection.iterator();
StringBuilder sb = new StringBuilder(iter.next());
while (iter.hasNext()) {
sb.append(seperator);
sb.append(iter.next());
}
return sb.toString();
}
#12
2
To avoid reinit(affect performance) of prefix
use TextUtils.isEmpty:
为避免重复使用前缀(影响性能),请使用textutilis . isempty:
String prefix = "";
for (String item : list) {
sb.append(prefix);
if (TextUtils.isEmpty(prefix))
prefix = ",";
sb.append(item);
}
#13
1
I personally like to append a backspace character (or more for longer "delimiter") at the end:
我个人喜欢在结尾添加一个退格字符(或更长的“分隔符”):
for(String serverId : serverIds) {
sb.append(serverId);
sb.append(",");
}
sb.append('\b');
Note that it has problems:
注意,它有以下问题:
- how
\b
is displayed depends on the environment, - b如何显示取决于环境,
- the
length()
of theString
content might be different from the length of "visibile" characters - 字符串内容的长度()可能与“visibile”字符的长度不同
When \b
looks OK and the length doesn't matter such as logging to a console, this seems good enough to me.
当\b看起来没问题,而且长度也不重要时,比如登录到控制台,这对我来说已经足够了。
#14
0
You may try to use 'Joiner' class instead of removing the last character from your generated text;
您可以尝试使用“Joiner”类,而不是从生成的文本中删除最后一个字符;
List<String> textList = new ArrayList<>();
textList.add("text1");
textList.add("text2");
textList.add("text3");
Joiner joiner = Joiner.on(",").useForNull("null");
String output = joiner.join(textList);
//output : "text1,text2,text3"
#15
0
Here is another solution:
这是另一个解决方案:
for(String serverId : serverIds) {
sb.append(",");
sb.append(serverId);
}
String resultingString = "";
if ( sb.length() > 1 ) {
resultingString = sb.substring(1);
}
#16
0
I am doing something like below:
我所做的事情如下:
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < value.length; i++) {
stringBuilder.append(values[i]);
if (value.length-1) {
stringBuilder.append(", ");
}
}
#1
494
Others have pointed out the deleteCharAt
method, but here's another alternative approach:
其他人指出了deleteCharAt方法,但这里有另一种方法:
String prefix = "";
for (String serverId : serverIds) {
sb.append(prefix);
prefix = ",";
sb.append(serverId);
}
Alternatively, use the Joiner
class from Guava :)
或者,使用Guava的Joiner类:)
As of Java 8, StringJoiner
is part of the standard JRE.
在Java 8中,StringJoiner是标准JRE的一部分。
#2
306
Another simple solution is:
另一个简单的解决方案是:
sb.setLength(sb.length() - 1);
A more complicated solution:
一个更复杂的解决方案:
The above solution assumes that sb.length() > 0
... i.e. there is a "last character" to remove. If you can't make that assumption, and/or you can't deal with the exception that would ensue if the assumption is incorrect, then check the StringBuilder's length first; e.g.
上述解决方案假设sb.length() >…也就是说,有一个“最后一个字符”要删除。如果你不能做那个假设,或者你不能处理一个例外,如果这个假设是错误的,那么首先检查StringBuilder的长度;如。
// Readable version
if (sb.length() > 0) {
sb.setLength(sb.length() - 1);
}
or
或
// Concise but harder-to-read version of the above.
sb.setLength(Math.max(sb.length() - 1, 0));
#3
122
sb.deleteCharAt(sb.length() - 1)
#4
48
As of Java 8, the String class has a static method join
. The first argument is a string that you want between each pair of strings, and the second is an Iterable<CharSequence>
(which are both interfaces, so something like List<String>
works. So you can just do this:
在Java 8中,String类有一个静态方法连接。第一个参数是在每一对字符串之间想要的字符串,第二个参数是一个Iterable
String.join(",", serverIds);
Also in Java 8, you could use the new StringJoiner
class, for scenarios where you want to start constructing the string before you have the full list of elements to put in it.
在Java 8中,您也可以使用新的StringJoiner类,在您想要开始构建字符串的场景中,您需要在将完整的元素列表放入其中之前开始构建字符串。
#5
33
In this case,
在这种情况下,
sb.setLength(sb.length() - 1);
is preferable as it just assign the last value to '\0'
whereas deleting last character does System.arraycopy
因为它只将最后一个值赋值为'\0',而删除最后一个字符是System.arraycopy
#6
24
Just get the position of the last character occurrence.
得到最后一个字符出现的位置。
for(String serverId : serverIds) {
sb.append(serverId);
sb.append(",");
}
sb.deleteCharAt(sb.lastIndexOf(","));
Since lastIndexOf
will perform a reverse search, and you know that it will find at the first try, performance won't be an issue here.
由于lastIndexOf将执行反向搜索,而且您知道它将在第一次尝试中发现,性能在这里不会成为问题。
#7
10
Another alternative
另一种替代方法
for(String serverId : serverIds) {
sb.append(",");
sb.append(serverId);
}
sb.deleteCharAt(0);
#8
10
With Java-8
you can use static method of String
class,
使用Java-8可以使用String类的静态方法,
String#join(CharSequence delimiter,Iterable<? extends CharSequence> elements)
.
字符串#加入(CharSequence进行分隔符,Iterable < ?扩展CharSequence进行>元素)。
public class Test {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("James");
names.add("Harry");
names.add("Roy");
System.out.println(String.join(",", names));
}
}
OUTPUT
输出
James,Harry,Roy
#9
6
Alternatively,
另外,
StringBuilder result = new StringBuilder();
for(String string : collection) {
result.append(string);
result.append(",");
}
return result.substring(0, result.length() - 1) ;
#10
5
StringBuilder sb = new StringBuilder();
sb.append("abcdef");
sb.deleteCharAt(sb.length() - 1);
assertEquals("abcde",sb.toString());
// true
#11
3
Yet another alternative:
另一个选择:
public String join(Collection<String> collection, String seperator) {
if (collection.isEmpty()) return "";
Iterator<String> iter = collection.iterator();
StringBuilder sb = new StringBuilder(iter.next());
while (iter.hasNext()) {
sb.append(seperator);
sb.append(iter.next());
}
return sb.toString();
}
#12
2
To avoid reinit(affect performance) of prefix
use TextUtils.isEmpty:
为避免重复使用前缀(影响性能),请使用textutilis . isempty:
String prefix = "";
for (String item : list) {
sb.append(prefix);
if (TextUtils.isEmpty(prefix))
prefix = ",";
sb.append(item);
}
#13
1
I personally like to append a backspace character (or more for longer "delimiter") at the end:
我个人喜欢在结尾添加一个退格字符(或更长的“分隔符”):
for(String serverId : serverIds) {
sb.append(serverId);
sb.append(",");
}
sb.append('\b');
Note that it has problems:
注意,它有以下问题:
- how
\b
is displayed depends on the environment, - b如何显示取决于环境,
- the
length()
of theString
content might be different from the length of "visibile" characters - 字符串内容的长度()可能与“visibile”字符的长度不同
When \b
looks OK and the length doesn't matter such as logging to a console, this seems good enough to me.
当\b看起来没问题,而且长度也不重要时,比如登录到控制台,这对我来说已经足够了。
#14
0
You may try to use 'Joiner' class instead of removing the last character from your generated text;
您可以尝试使用“Joiner”类,而不是从生成的文本中删除最后一个字符;
List<String> textList = new ArrayList<>();
textList.add("text1");
textList.add("text2");
textList.add("text3");
Joiner joiner = Joiner.on(",").useForNull("null");
String output = joiner.join(textList);
//output : "text1,text2,text3"
#15
0
Here is another solution:
这是另一个解决方案:
for(String serverId : serverIds) {
sb.append(",");
sb.append(serverId);
}
String resultingString = "";
if ( sb.length() > 1 ) {
resultingString = sb.substring(1);
}
#16
0
I am doing something like below:
我所做的事情如下:
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < value.length; i++) {
stringBuilder.append(values[i]);
if (value.length-1) {
stringBuilder.append(", ");
}
}