Yos*_*199 0 java string comparison
我得到了这个字符串比较的问题。我必须编写一种方法来比较两个字符串,而不使用 java 的内置字符串比较方法。它也假设大约有 3 - 5 行代码。该方法应该返回 0 表示相等,1 表示字符串 'a' 大于字符串 'b',-1 表示字符串 'a' 小于 'b'
现在,我知道 Java 会根据int每个字符的值来比较字符串,所以我尝试做这件事,虽然可行,但绝对不是 3-5 行代码:
public int compare(String s1, String s2){
int result = 0;
int count = 0; // The counter for the first string integer values sum
int count2 = 0; // The counter for the second string integer values sum
for(int c=0; c<s1.length(); c++){
count = count +s1.charAt(c);
}
for (int c2=0; c2<s2.length(); c2++){
count2 = count2 +s2.charAt(c2);
}
//***** some condition statement to check which is bigger and then return the result
Run Code Online (Sandbox Code Playgroud)
您是否考虑过进行简单的字典比较而不是比较长度(或者无论您尝试做什么,都不是特别容易分辨):
for(int i=0; i<a.length() && i<b.length(); i++) {
if(a.charAt(i) != b.charAt(i))
return a.charAt(i) < b.charAt(i) ? -1 : 1;
}
return a.length() < b.length() ? -1 : a.length() == b.length() ? 0 : 1;
Run Code Online (Sandbox Code Playgroud)
这与java.lang.Strings 所做的基本相同,只是它只使用公共方法。