C# string.Replace doesn't work

2019-06-10 03:52发布

Basically our Problem is: We can't replace a string like this: 10003* But we can replace a string like this: 10003

we want to replace a part of a string that looks like this: 10003* This is our Code:

string text = sr2.ReadToEnd();
sr2.Close();
while (loop != lstTxt.Items.Count)
{
    string SelectedItem = lstTxt.SelectedItem.ToString() + "*";

    text = text.Replace(SelectedItem, "tietze111");


    if (lstTxt.SelectedIndex < lstTxt.Items.Count - 1)
        lstTxt.SelectedIndex++;
    loop++;

}

sw2.Write(text);

But it doesn't work. When we leave out the * in the part to replace, it works. But we have to replace the * too. Do you know what we have to change?

It works when we use this:

string text = sr2.ReadToEnd();
sr2.Close();
while (loop != lstTxt.Items.Count)
{
    string SelectedItem = lstTxt.SelectedItem.ToString(); // changed

    text = text.Replace(SelectedItem, "tietze111");


    if (lstTxt.SelectedIndex < lstTxt.Items.Count - 1)
        lstTxt.SelectedIndex++;
    loop++;

}

sw2.Write(text);

-- using (var sr2 = new StreamReader(Application.StartupPath + @"\website\Dehler 22 ET.htm", Encoding.Default)) {

                using (var sw2 = new StreamWriter(tempFile, true, Encoding.Default))

We are using this because the file is still in ASCII. Maybe that is the problem. How do we solve this?

4条回答
手持菜刀,她持情操
2楼-- · 2019-06-10 04:30

The String.Replace(String,String) method doesn't do anything special with any characters. There is a character in your id that you are trying to replace is not the same as the one you are trying to match on. I would try copying the astrisk from the data source into your code and see if the problem still exists.

查看更多
一夜七次
3楼-- · 2019-06-10 04:36

Your problem * is encoded in some other type. The Unicode value for asterisk U+002A

You could try this. Note Char.MinValue is technically a null value since you cannot have a blank Char.

In your case: lstTxt.SelectedItem.ToString() + '\u002A'.ToString();

If that doesn't work try removing (using different encoded values for *) to make sure you can actually find it in the string.

SomeString.Replace('\u002A', Char.MinValue);

OR

SomeString.Replace('\u002A'.ToString(), String.Empty);

I've ran into issues like this before and it ends up being a trial and error kind of thing until you get it right. Similar problem I had last summer C# String.Replace not finding / replacing Symbol (™, ®)

查看更多
forever°为你锁心
4楼-- · 2019-06-10 04:37

Have you tried?

"[\*]"

Or

@"[*]" 
查看更多
霸刀☆藐视天下
5楼-- · 2019-06-10 04:42

Fix the following line,

string SelectedItem = lstTxt.SelectedItem.Value;

You are taking the item and not the value.

查看更多
登录 后发表回答