替换列表框中的子字符串(Windows 窗体)

Replace substring from the listbox (WindowsForms)

我在我的列表框 ( lb1 ) 中为上一项附加了一个字符。字母 A 由逗号分隔。是否有可能替换这一行中的字母 (A--> B)?如何解决?列表框 ( lb2 ) 中的结果应如下所示。

if (listBox1.Items.Cast<string>().Contains("someText"))
{
    int a = listBox1.Items.IndexOf("someText");
    listBox1.Items.RemoveAt(a);
    listBox1.Items.Insert(a, "newText");
}

这是您的新问题 mikee 的代码片段:

您需要遍历列表框的项目,搜索匹配项,并替换检测到的匹配项:

string search = "A";
string replace = "B";

for(int i = 0; i < lb1.Items.Count; i++)
{
    if(lb1.Items[i].ToString().EndsWith(search))
    {
        string item = lb1.Items[i].ToString().Replace(search, replace);
        lb1.Items[i] = item;
    }
}

编辑

请注意,前面的代码片段会将字符串中的所有 A 字符更改为 B,而不仅仅是最后一个。因此,如果您有一个列表项 JONATHAN, A,前面的代码会将其更改为 JONBTHBN, B。为避免这种情况,您可以这样做:

解决方案一:

for (int i = 0; i < lb1.Items.Count; i++)
{
    if (lb1.Items[i].ToString().EndsWith(search))
    {
        int indx = lb1.Items[i].ToString().LastIndexOf(search);
        string item = lb1.Items[i].ToString().Substring(0, indx) + replace;
        lb1.Items[i] = item;
    }
}

方案二:

如果您的所有列表项都是逗号分隔的字符串,如上图,那么您可以这样做:

for (int i = 0; i < lb1.Items.Count; i++)
{
    if (lb1.Items[i].ToString().EndsWith(search))
    {
        var arr = lb1.Items[i].ToString().Split(',');
        arr[arr.Length - 1] = replace;

        lb1.Items[i] = string.Join(", ", arr);
    }
}

对于给您带来的不便,迈克,我们深表歉意。

祝你好运。