C# string.Replace 不起作用 [英] C# string.Replace doesn't work

查看:75
本文介绍了C# string.Replace 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我们的问题是:我们不能替换这样的字符串:10003*但是我们可以像这样替换一个字符串:10003

我们想要替换如下所示的字符串的一部分: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);

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

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

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

我们使用它是因为文件仍然是 ASCII.也许这就是问题所在.我们如何解决这个问题?

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

推荐答案

您的问题 * 以其他类型编码.星号 U+002A 的 Unicode 值

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

你可以试试这个.注意 Char.MinValue 在技术上是一个空值,因为你不能有一个空白的 Char.

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

在你的情况下: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);

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

我以前也遇到过这样的问题,但最终还是要反复试验,直到你做对了.我去年夏天遇到了类似的问题 C# String.Replace 没有找到/替换符号(™, ®)

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 (™, ®)

这篇关于C# string.Replace 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆