【问题标题】:IndexOf() vs Replace() and zero-width non-joinerIndexOf() vs Replace() 和零宽度非连接器
【发布时间】: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


【解决方案1】:

说明

String.Replace(String,string)doco doco 声明:

此方法执行序数(区分大小写和不区分区域性)搜索以查找 oldValue。

String.IndexOfsource code 表明它使用了StringComparison.CurrentCulture

public int IndexOf(String value) {
            return IndexOf(value, StringComparison.CurrentCulture);
        }

做什么

在 .NET 核心中,您可以使用 InvariantCulture 来完成此操作

string replaced = str.Replace("bc", "BC", StringComparison.InvariantCulture); 

【讨论】:

  • +1,或int index = str.IndexOf("bc", StringComparison.Ordinal) 可以看到IndexOf的相反效果
  • 是的,IndexOf 默认使用StringComparison.CurrentCulture
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-27
  • 2014-02-12
  • 1970-01-01
  • 2021-12-05
  • 1970-01-01
  • 2010-11-29
  • 2013-01-13
相关资源
最近更新 更多