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

IndexOf() vs Replace() and zero-width non-joiner

为什么 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 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);