为什么 IndexOf()
会忽略零宽度非连接符 char
,而 Replace()
不会:
class Program
{
static void Main(string[] args)
{
const string zeroWidthNonJoiner = "\u200C";
string str = $"ab{zeroWidthNonJoiner}cd";
int index = str.IndexOf("bc"); //index = 1 (does ignore the zeroWidthNonJoiner)
string replaced = str.Replace("bc", "BC"); //replaced = "abcd" (does NOT ignore the zeroWidthNonJoiner)
}
}
最佳答案
说明
String.Replace(String,string)
的 doco多科状态:
This method performs an ordinal (case-sensitive and culture-insensitive) search to find oldValue.
String.IndexOf
的 source code显示它使用 StringComparison.CurrentCulture
public int IndexOf(String value) {
return IndexOf(value, StringComparison.CurrentCulture);
}
做什么
在 .NET 核心中,您可以使用 InvariantCulture
string replaced = str.Replace("bc", "BC", StringComparison.InvariantCulture);
关于c# - IndexOf() 与 Replace() 和零宽度非连接器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58369925/