I have just faced this problem today and wonder if someone has any idea about why does this test may fail (depending on culture). The aim is to check if the test text contain two spaces next to each other, which does according to string.IndexOf (even if i tell the string to replace all occurrences of two spaces next to each other). After some testing it seems \xAD is somehow causing this issue.
public class ReplaceIndexOfSymmetryTest
{
[Test]
public void IndexOfShouldNotFindReplacedString()
{
string testText = "\x61\x20\xAD\x20\x62";
const string TWO_SPACES = " ";
const string ONE_SPACE = " ";
string result = testText.Replace(TWO_SPACES, ONE_SPACE);
Assert.IsTrue(result.IndexOf(TWO_SPACES) < 0);
}
}
Yes, I’ve come across the same thing before (although with different characters). Basically
IndexOfwill take various aspects of “special” Unicode characters into account when finding matches, whereasReplacejust treats the strings as a sequence of code points.From the
IndexOfdocs:… and from
Replace:You could use the overload of
IndexOfwhich takes aStringComparison, and force it to perform an ordinal comparison though.