C# string.IndexOf 方法不起作用

C# string.IndexOf method doesn't work

我正在使用 C# 从字符串中删除特殊字符:

while (str.Contains("@"))
    str = str.Remove(str.IndexOf("@"), 1);

但这会产生错误:

StartIndex can not be less than zero.

str变量确实包含@个字符,但IndexOf()方法的结果值为-1。

我猜是因为字符串编码是utf-8,但我不知道如何操作字符串。

str的值为NfyCAlcvxu1Xqw@ًں‘„ًں

您单独提供的那段代码似乎没问题。

但是,我建议采用不同的方法来解决这个问题:

C#

str = str.Replace("@", "");

来自 string.Contains

的 MSDN

This method performs an ordinal (case-sensitive and culture-insensitive) comparison. The search begins at the first character position of this string and continues through the last character position.

因此您还必须在 IndexOf 中使用序号比较:

while (str.Contains("@"))
    str = str.Remove(str.IndexOf("@",StringComparison.Ordinal), 1);