2016-03-28 19 views
0

,而我是學習(閱讀基本C#6第五版)的String.Compare()方法,我讀了,如果我有讓說,1串text1和1串text2比較,我得到一個號碼時:String.Compare()2串

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

所以,當我做到這一點

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

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

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

但是,如果我這樣做:

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? 

爲什麼會發生這種情況,或者我錯過了(弄亂)某物/某物?

+0

相關http://stackoverflow.com/questions/9354966/string-sorting-issue-in-c-sharp – LibertyLocked

+1

找到你見過詞典(像一本書)? 「Helo」>「你好」... –

回答

2

它比較每個字符的消退順序:H = H,E = E,L = L,O> L然後停止。所以Helo>Hello只是因爲l是在o之前的字母表。

更多信息可以在MSDN

+0

哦,我認爲它比較了兩個字符串含義數字是否有相同的字符,例如1個字符串中的5個字符和另一個字符串中的5個字符。 – Johnson

+0

或者我誤以爲String.Equals()方法? – Johnson

+0

不會。它實際上會比較字符串中每個字符的ASCII碼。如果你需要比較字符串的長度,你可以使用這樣的東西:'text1.Length> text2.Length' –