【发布时间】:2014-10-24 18:16:59
【问题描述】:
我必须编写一个方法来按字母顺序比较字符串并返回int。我不能使用任何内置函数,我应该使用for 循环。
我不确定如何处理不同长度的字符串。目前我的主要问题是代码只比较每个字符串的第一个字符然后返回 int,但我不能将 return comparison; 放在 for 循环之外
public class poop {
public static int Compare(String s1, String s2) {
for (int i = 0; i < s1.length() && i < s2.length(); i++) {
int comparison = 0;
int ascii1 = 0;
int ascii2 = 0;
//convert chars into their ascii values
ascii1 = (int) s1.charAt(i);
ascii2 = (int) s2.charAt(i);
//treat capital letters as lower case
if (ascii1 <= 95) {
ascii1 += 32;
} if (ascii2 <= 95) {
ascii1 += 32;
}
if (ascii1 > ascii2) {
comparison = 1;
} else if (ascii1 < ascii2) {
comparison = -1;
} else {
comparison = 0;
}
}
return comparison;
}
public static void main(String[] args) {
String s1 = "aba";
String s2 = "aaa";
System.out.println(Compare(s1,s2));
}
}
【问题讨论】:
-
“我不能将返回比较放在 for 循环之外”...为什么不呢?
-
breakit 在 if 语句中,您可以将return comparison移出循环 -
处理比较,只需要在for循环之外定义它..
-
如果你要比较两个字符串并且你不能使用任何“内置”函数,那么你就完蛋了。您至少需要使用
charAt或getChars来访问数据。当然,您不能使用length来找出字符串的长度。