From 8a4d3effe0d4a4f83ed855d824aecbe770a1a2a2 Mon Sep 17 00:00:00 2001 From: Eric Scharff Date: Fri, 28 Sep 2007 11:00:31 -0600 Subject: [PATCH] Make String.compare() match the Java specification --- classpath/java/lang/String.java | 43 +++++++++++++++++---------------- 1 file changed, 22 insertions(+), 21 deletions(-) diff --git a/classpath/java/lang/String.java b/classpath/java/lang/String.java index 283e4b7248..94c7339673 100644 --- a/classpath/java/lang/String.java +++ b/classpath/java/lang/String.java @@ -89,36 +89,37 @@ public final class String implements Comparable { public int compareTo(String s) { if (this == s) return 0; - int d = length - s.length; - if (d != 0) { - return d; - } else { - for (int i = 0; i < length; ++i) { - d = charAt(i) - s.charAt(i); - if (d != 0) { - return d; - } + int idx = 0; + int result; + + int end = (length < s.length ? length : s.length); + + while (idx < end) { + if ((result = charAt(idx) - s.charAt(idx)) != 0) { + return result; } - return 0; + idx++; } + return length - s.length; } public int compareToIgnoreCase(String s) { if (this == s) return 0; - int d = length - s.length; - if (d != 0) { - return d; - } else { - for (int i = 0; i < length; ++i) { - d = Character.toLowerCase(charAt(i)) - - Character.toLowerCase(s.charAt(i)); - if (d != 0) { - return d; - } + int idx = 0; + int result; + + int end = (length < s.length ? length : s.length); + + while (idx < end) { + if ((result = + Character.toLowerCase(charAt(idx)) - + Character.toLowerCase(s.charAt(idx))) != 0) { + return result; } - return 0; + idx++; } + return length - s.length; } public String trim() {