我被问到了这个字符串比较的问题。我不得不编写一个方法来比较两个字符串,而不使用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发布于 2014-07-16 13:47:59
你有没有考虑过做一个简单的字典比较,而不是比较长度(或者不管你想做什么,它并不是特别容易分辨):
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;这与java.lang.String所做的基本相同,只是它只使用公共方法。
发布于 2014-07-16 13:11:57
考虑到2 String a和b,解决方案可能是:
int comp = 0;
for(int i = 0; i < Math.min(a.length(), b.length()); i++)
if((comp = a.charAt(i) - b.charAt(i)) != 0)
return comp;
return a.length() < b.length() ? -1 : a.length() == b.length() ? 0 : 1;它计算每个char在相同位置上的差异,直到较小的String长度,如果它们都是0,则返回较小的String。
编辑:我不知道投反对票的原因可能是什么,但无论如何,在一个快速测试中,它能像预期的那样工作(而且它有5行长)。
发布于 2014-07-16 13:31:25
我认为这种递归方法可能适用于您:
public static int compare(String a, String b, int pos){
if(a.charAt(pos) == b.charAt(pos) && pos >= a.length() && pos >= b.length())
return 0;
else if(a.charAt(pos) > b.charAt(pos))
return 1;
else if(a.charAt(pos) < b.charAt(pos))
return -1;
else {
pos++;
if(pos < a.length() && pos < b.length())
return compare(a,b,pos);
else if(pos < a.length() && pos >= b.length())
return 1;
else if(pos >= a.length() && pos < b.length())
return -1;
else return 0;
}
}您必须在main上使用变量compare调用0上的0方法,如下所示:
public static void main(String[] args) {
String a = "azzz";
String b = "azz";
System.out.println("" + compare(a,b,0));
}希望这能有所帮助。
https://stackoverflow.com/questions/24781254
复制相似问题