本文介绍了如何从字符串中删除结尾的逗号(Java)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,我在每个循环中使用a进行迭代.然后,我将其存储在字符串中,然后尝试在其中添加逗号,但是正在努力寻找基于逻辑"的解决方案.

I have an array, which I use a for each loop to iterate through. I then store it in a string and then try to add a comma to it, but am struggling look for a "logic" based solution.

我几乎要花大约1年时间才能使用Java,所以我现在试图找到实现的大多数解决方案都是基于逻辑的(目前),因为这是Java MOOC的一部分.我可以看些什么选择?我想念什么?

I am almost close to about 1 year's worth of Java under my belt, so most of the solutions I am trying to find to implement are mostly logic based (for now), since this is apart of Java MOOC's course. What are some options I can look at? What am I missing?

for(int number: array){
    String thread = "";
    thread += number + ", ";
    System.out.print(thread);
}

推荐答案

我不确定该项目对您的课程有何限制,但如果可以,请尝试使用 StringJoiner !它将自动添加定界符以分隔添加到其中的项目.另一个注意事项,我想您将要在for循环外声明您的String.否则,它将重置每次迭代.

I'm not sure the constraints of this project for your course, but if you're able, try a StringJoiner! It will add a delimiter automatically to separate items that are added to it. Another note, I think you're going to want to declare your String outside of your for loop. otherwise it resets every iteration.

StringJoiner joiner = new StringJoiner(",");
for(int number : array){
 joiner.add(String.valueOf(number));
}
     System.out.print(joiner.toString());

这篇关于如何从字符串中删除结尾的逗号(Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 10:46