20220406Java字串操作類中scompareTo()

darkhui發表於2022-04-06

記個筆記

字串操作類中s1.compareTo(s)規則

 

Compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The character sequence represented by this String object is compared lexicographically to the character sequence represented by the argument string. The result is a negative integer if this String object lexicographically precedes the argument string. The result is a positive integer if this String object lexicographically follows the argument string. The result is zero if the strings are equal; compareTo returns 0 exactly when the equals(Object) method would return true.

 

This is the definition of lexicographic ordering. If two strings are different, then either they have different characters at some index that is a valid index for both strings, or their lengths are different, or both. If they have different characters at one or more index positions, let k be the smallest such index; then the string whose character at position k has the smaller value, as determined by using the < operator, lexicographically precedes the other string. In this case, compareTo returns the difference of the two character values at position k in the two string -- that is, the value:

 

 this.charAt(k)-anotherString.charAt(k)
 

If there is no index position at which they differ, then the shorter string lexicographically precedes the longer string. In this case, compareTo returns the difference of the lengths of the strings -- that is, the value:

 this.length()-anotherString.length()
 

 

1.當字串s1和s都表示數字時,有三種結果-1(代表s1<s) ,  0(代表s與s1相等)  ,1(代表s1>s)。

2.當字串s1和s不表示數字時,有三種結果負整數 (代表s1和s中的第一個不相同的字元的Unicode值相減為負數),0(代表s與s1相等) ,

正整數(代表s1和s中的第一個不相同的字元的Unicode值相減為正數);若s1包含s(即s中的字元,s1都有),也有上述三種結果

但意義不同(除0表示相等)其中正整數表示s1包含s且長度大於s;反之為負整數。

3.Unicode中 a表示61   A表示41其它字母類推。

最後總結英語是有必要學的!

 

相關文章