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

Viewed 367

Why does IndexOf() ignore the zero-width non-joiner char, but Replace() doesn't:

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)

    }
}
1 Answers

Explanation

String.Replace(String,string)'s doco doco states:

This method performs an ordinal (case-sensitive and culture-insensitive) search to find oldValue.

String.IndexOf's source code shows that it uses StringComparison.CurrentCulture

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

What to do

In .NET core you can do it with InvariantCulture

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