1

while i was learning (reading Essential C# 6 5th Edition) the String.Compare() method i read that if i have lets say 1 string text1 and 1 string text2 when comparing that i get a number:

// 0 if equal
// negative if text1 < text2
// positive if text1 > text2

so when i do this

string text1 = "Hello";
string text2 = "Hello";

int result = string.Compare(text1, text2);

Console.Write(result); // I get 0 which means equal which is correct.

But if i do:

string text1 = "Helo";
string text2 = "Hello";

int result = string.Compare(text1, text2);

Console.Write(result); // I get 1. Shouldn't i be getting -1? Doing the opposite meaning that i have text1 = "Hello" and text 2 = "Helo" produces -1 when it should produce 1 correct?

Why does that happen or am i missing (messing) something/with something?

Johnson
  • 401
  • 5
  • 14

1 Answers1

3

It compares each character in the appering order: H = H, E = E, L = L, O > L and then it stops. So Helo > Hello simply because l is before o in the alphabet.

More info can be found on MSDN

Alexandru Chichinete
  • 1,166
  • 12
  • 23
  • Oh i thought it compares to see if there are equal characters in both string meaning numbers for example 5 characters in 1 string and 5 in another. – Johnson Mar 28 '16 at 20:03
  • Or am i mistaking it with the String.Equals() method? – Johnson Mar 28 '16 at 20:05
  • No. It compares the ASCII code for each character in the string actually. If you need to compare the length of string you can use something like this: `text1.Length > text2.Length` – Alexandru Chichinete Mar 28 '16 at 20:05
  • `String.Equls` compare you string and if they are equal then it returns `true` else `false`. `String.Equals(text1, text2)` is like `String.Compare(text1, text2) == 0` – Alexandru Chichinete Mar 28 '16 at 20:07
  • Thanks chosen best answer only 1 thing if you can help understand a usage where String.Compare would be useful. Why would someone want to compare individual characters inside a string. Like it seams to me extremely rare where there would be a usage to compare e.g. helo to hello and get that helo is bigger. Or is it indeed used for those rare cases? – Johnson Mar 28 '16 at 20:11
  • 1
    @GeorgeOscStephan To put strings in alphabetical order like you would find them in a dictionary. That's not rare at all. – juharr Mar 28 '16 at 20:14