Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 删除循环后的文本_C#_String - Fatal编程技术网

C# 删除循环后的文本

C# 删除循环后的文本,c#,string,C#,String,我有一个for循环,它在字符串的末尾添加一个单选按钮文本。代码如下: for (int i = 0; i < listView1.CheckedItems.Count; i++) { sqlQry.Text += listView1.CheckedItems[i].Text + radioButton9.Text; } 现在的结果是:A和B,C和 我希望它是:A、B和C 我确实尝试

我有一个for循环,它在字符串的末尾添加一个单选按钮文本。代码如下:

for (int i = 0; i < listView1.CheckedItems.Count; i++)
                {
                    sqlQry.Text += listView1.CheckedItems[i].Text + radioButton9.Text;
                }  
现在的结果是:A和B,C和 我希望它是:A、B和C 我确实尝试了我提到的代码,但我无法使用:

sQlQry.Text=sqlQry.Text.TrimEnd(radioButton9.Text);

使用不同的逻辑要容易得多,这样您就不会首先将分隔符放在末尾

for (int i = 0; i < listView1.CheckedItems.Count; i++)
{
   if(i != 0)
   {
      // Put separator in before this thing 
      // when this is not the first thing we add.
      sqlQry.Text += radioButton9.Text;
   }
   sqlQry.Text += listView1.CheckedItems[i].Text;
}  

您可以获取radioButton9.Text的长度,并对其执行子字符串 您的sqlQry.Text

sqlQry.Text.Substring(0, sqlQry.Text.Length - radioButton9.Text.Length);
简单解决方案:。 示例:sqlQry.Substring0,sqlQry.Length-/*fixedLength*/radioButton9.Text.Length 这将返回一个字符串,该字符串从末尾减去固定数量的字符。Updated去掉radioButton9文本属性的长度。

您可以使用string.Join


对这只适用于字符。你试过你要求的吗?字符串怎么样?加入而不是循环?为什么不做类似的操作:String.JoinradioButton9.Text,listView1.CheckedItems看起来像@Pikoh击败了我=很抱歉@TimSchmelter,但它会编译。ListView.CheckedItems是ListViewItem的集合,它确实有一个文本属性
sqlQry.Text.Substring(0, sqlQry.Text.Length - radioButton9.Text.Length);
sqlQry.Text = string.Join(radioButton9.Text, listView1.CheckedItems.Cast<ListViewItem>().Select(x => x.Text));