String 的 compareTo 方法

来源:互联网 发布:淘宝会员名是什么意思 编辑:程序博客网 时间:2024/05/22 11:46

Compares the specified stringto this string using the Unicode values of

the characters. Returns 0 ifthe strings contain the same characters in

the same order. Returns anegative integer if the first non-equal

character in this string hasa Unicode value which is less than the

Unicode value of thecharacter at the same position in the specified

string, or if this string isa prefix of the specified string. Returns apositive integer if the first non-equal character inthis string has aUnicode value which isgreater than the Unicode value of the character atthe same position in the specified string, or if thespecified string isprefix of this string.



public int compareTo(String string) {
        // Code adapted from K&R, pg 101
        int o1 = offset, o2 = string.offset, result;
        int end = offset + (count < string.count ? count : string.count);
        char[] target = string.value;
        while (o1 < end) {
            if ((result = value[o1++] - target[o2++]) != 0) {
                return result;
            }
        }
        return count - string.count;
    }

原创粉丝点击