托架不断偷偷溜进来!为什么?

时间:2013-05-28 20:33:23

标签: c# .net winforms io

我有一个文件中的行列表'我正在阅读它们,它们看起来像这样:

[something]:[here]
[something]:[here]
[something]:[here]
[something]:[here]

现在,下面的代码基本上确定列表中的任何内容是否在TextBox中,如果文本框中包含“key”,则该键将替换为键的值。

        string key, value, tempLine = "";

        using (StringReader reader = new StringReader(list))
        {
            string line;
            string[] split;
            while ((line = reader.ReadLine()) != null)
            {
                // Do something with the line.
                tempLine = line.Replace("[", "");
                tempLine = tempLine.Replace("]", "");

                split = tempLine.Split(':');
                key = split[0];
                value = split[1];
                    key = key.Replace(@"[", "");
                    key = key.Replace(@"]", "");
                    value = value.Replace(@"[", "");
                    value = value.Replace(@"]", "");
                if (((TextBox)tabControl1.SelectedTab.Controls[0]).Text.Contains("[" + key + "]"))
                {

                    ((TextBox)tabControl1.SelectedTab.Controls[0]).Text = ((TextBox)tabControl1.SelectedTab.Controls[0]).Text.Replace(key, value);
                }
            }
        }

现在我遇到的问题是,无论我做什么 - 括号([和])都会不断回来!

请问,我试图摆脱一串括号的方式有什么问题吗?如何让它们消失?

2 个答案:

答案 0 :(得分:4)

似乎您正在搜索由[key]组成的占位符到您的文本框中,但是当替换时,该值只会替换密钥,保持[]完好无损。

您必须用此代码替换您的代码......

if (((TextBox)tabControl1.SelectedTab.Controls[0]).Text.Contains("[" + key + "]"))
{
    ((TextBox)tabControl1.SelectedTab.Controls[0]).Text = ((TextBox)tabControl1.SelectedTab.Controls[0]).Text.Replace("[" + key + "]", value);
}

并且不要将[]个字符替换两次。没有必要。

使用您的代码作为基线,生成的代码必须是:

string key, value, tempLine = "";

using (StringReader reader = new StringReader(list))
{
    string line;
    string[] split;
    while ((line = reader.ReadLine()) != null)
    {
        // Do something with the line.
        split = line.Split(':');
        key = split[0];
        value = split[1].Replace("[", "").Replace("]", "");

        if (((TextBox)tabControl1.SelectedTab.Controls[0]).Text.Contains(key))
        {
            ((TextBox)tabControl1.SelectedTab.Controls[0]).Text = ((TextBox)tabControl1.SelectedTab.Controls[0]).Text.Replace(key, value);
        }
    }
}

答案 1 :(得分:1)

也许试试:

((TextBox)tabControl1.SelectedTab.Controls[0]).Text = ((TextBox)tabControl1.SelectedTab.Controls[0]).Text.Replace("[" + key + "]", value);