【发布时间】:2019-10-14 03:56:52
【问题描述】:
为什么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)
}
}
【问题讨论】:
-
Replace的文档指定:“此方法执行顺序(区分大小写和不区分区域性)搜索以查找 oldValue。”,而对于IndexOf:“此方法执行一个单词(区分大小写和区域性)使用当前区域性进行搜索。" -
这是一个已知问题,主要是因为用户从 html 页面复制内容并粘贴到各种格式的工件中(还有在没有更高级别协议时使用这些格式控制字符的文本文件可用的)。如果您需要接受来自 the wild 的输入,则需要一个去除 unicode 字符(和标准控制代码)范围的 cleaner proc。
标签: c# .net string .net-4.7.2