Minimum string as per String#CompareTo

前端 未结 5 867
轮回少年
轮回少年 2021-01-20 16:07

Ok, I\'m sure that this must exist on here somewhere, but I can\'t seem to find it.

Is there, and if there is what is, a minimum (non-null) String seque

5条回答
  •  不知归路
    2021-01-20 16:43

    Edit:

    Try this,

       String s="";
          String s1=new String(new char[-2]);  // Here you will get NagativeArraySize Exception
         System.out.println(s1.compareTo(s));
    

    Here compareTo returns nothing in System.out.println(), so the minimum string will be "" or String.Empty


    AFAIK, There is no minimum lenght and you can not find a string with the length <0, so the minimum length for the string 0 (string.Empty or "").

    Check this source code of CompareTo ,

    public int compareTo(String anotherString) {
            int len1 = count;       // original string count
            int len2 = anotherString.count;  // comparision string count
            int n = Math.min(len1, len2);       
            char v1[] = value;
            char v2[] = anotherString.value;
            int i = offset;
            int j = anotherString.offset;
    
            if (i == j) {
                int k = i;
                int lim = n + i;
                while (k < lim) {
                    char c1 = v1[k];
                    char c2 = v2[k];
                    if (c1 != c2) {
                        return c1 - c2;
                    }
                    k++;
                }
            } else {
                while (n-- != 0) {
                    char c1 = v1[i++];
                    char c2 = v2[j++];
                    if (c1 != c2) {
                        return c1 - c2;
                    }
                }
            }
            return len1 - len2;
        }
    

提交回复
热议问题