c# - IndexOf() 与 Replace() 和零宽度非连接器

标签 c# .net string .net-4.7.2

为什么 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.IndexOfsource 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/

相关文章:

c# - 使用 LINQ 的最佳序列

c# - 无法在C#中为列表添加值

c# - 从 ADUser 获取 UserPrincipal

c# - 可视化 WPF 控件中的对象属性

c++ - 在 LCD 上显示整数

java - String.intern() 的垃圾收集行为

c# - EF CodeFirst 设置默认字符串长度并使用 DataAnnotations 覆盖?

c# - JSQMessagesViewController 找不到 heightForCellTopLabelAtIndexPath

c# - .NET 方法(在 .dll 中)和反射(reflect)版本之间的性能差异

r - R中find_replace nul字符