C# 字符串.替换不起作用

本文关键字:不起作用 替换 字符串 | 更新日期: 2023-09-27 18:32:40

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

我们要替换如下所示的字符串的一部分:10003*这是我们的准则:

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);

但它不起作用。当我们省略要替换的部分中的 * 时,它可以工作。但我们也必须替换 *。你知道我们必须改变什么吗?

当我们使用它时,它有效:

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))

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

C# 字符串.替换不起作用

修复以下行,

string SelectedItem = lstTxt.SelectedItem.Value;

您拿的是物品而不是价值。

你试过吗?

"['*]"

@"[*]" 

String.Replace(String,String) 方法不会对任何字符执行任何特殊操作。您的 id 中有一个您尝试替换的字符与您尝试匹配的字符不同。我会尝试将星号从数据源复制到您的代码中,看看问题是否仍然存在。

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

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

在您的情况下:lstTxt.SelectedItem.ToString() + ''u002A'.ToString();

如果这不起作用,请尝试删除(对 * 使用不同的编码值)以确保您实际上可以在字符串中找到它。

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

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

我以前遇到过这样的问题,它最终是一个反复试验的事情,直到你做对了。去年夏天我遇到了类似的问题 C# 字符串.替换找不到/替换符号 (™, ® )