Ahmed
Ahmed

Reputation: 7248

String.StartsWith does not work as I expect

string word1 = ""; //see example   
string word2 = "";    
bool b1 = word1.StartsWith(word2);
bool b2 = word1.Substring(0, word2.Length) == word2;

for some Arabic strings b1 does not equal b2? Could you explain this behavior?

Example:

word1 = ((char)0x0650).ToString()+ ((char)0x0652).ToString()+ ((char)0x064e).ToString();
word2 = ((char)0x0650).ToString()+ ((char)0x0652).ToString();

Upvotes: 1

Views: 5814

Answers (1)

Hans Kesting
Hans Kesting

Reputation: 39338

There is a difference: .StartsWith performs a culture sensitive comparison, while .Equals (what you use with ==) doesn't.

So if you have two strings, that are different when you compare them character-by-character (== returns false), but are considered equal by your culture (startswith returns true), you could get this result.

EDIT If I try your example values with this:

bool b1 = word1.StartsWith(word2, StringComparison.Ordinal);
bool b2 = word1.Substring(0, word2.Length).Equals(word2, StringComparison.Ordinal);

both return "True".

Upvotes: 7

Related Questions