如何在项目之间加入“,”?

时间:2014-09-07 18:42:50

标签: c# string

好的,我的代码在这里:

string value = "";
foreach (var item in listBox1.Items)
{
    value += "," + item.ToString();
}
textBox3.Text = value;

我只想在第一个单词之后的","这样 "Test, Test, Test" 相反,它这样做 ",Test,Test,Test"

4 个答案:

答案 0 :(得分:7)

使用String.Join

  

使用每个元素或成员之间的指定分隔符连接指定数组的元素或集合的成员。

示例:

textBox3.Text = String.Join(", ", listBox1.Items.Cast<object>());

(感谢@EZI和@ Selman22指出代码中的问题)

答案 1 :(得分:5)

如果您发现其他答案无法编译,那么答案就在这里

textBox3.Text = String.Join(",", listBox1.Items.Cast<string>());

如果你想以经典的方式做到这一点

string value = "";
foreach (var item in listBox1.Items)
{
    value += item.ToString() + ",";
}
textBox3.Text = value.TrimEnd(',');

答案 2 :(得分:0)

如果你想尽可能地坚持原始代码,你可以在这里做两件基本事情----- 1) string value = ""; foreach (var item in listBox1.Items) { value += "," + item.ToString(); } value.Remove(0,1); //removes the 1st character, which is the offending "," textBox3.Text = value;

2) string value = ""; foreach (var item in listBox1.Items) { value += item.ToString() + ","; //swaps original order of the item and "," } value.Remove(value.length - 1,1); //removes last character, which will be a "," textBox3.Text = value;

答案 3 :(得分:0)

在for循环结束时,使用

value = value.substring(1);

只删除第一个字符。