public class Strcmp {
public static void main(String[] args) {
String a="aasdf";
String b="sdfad";
String c="aasdfg";
System.out.println(compareString(b,b));
}
/**
* 比较两个字符串大小
* 相等返回0,a大返回1,a小返回-1
* <p>
* 思路:取出共同长度进行比较
* 然后比长度
*/
public static int compareString(String a, String b) {
int comLength = a.length() > b.length() ? b.length() : a.length();
for (int i = 0; i < comLength - 1; i++) {
if (a.charAt(i) > b.charAt(i)) {
return 1;
}
if (a.charAt(i) < b.charAt(i)) {
return -1;
}
}
if (a.length() > b.length()) {
return 1;
} else if (a.length() == b.length()) {
return 0;
} else {
return -1;
}
}
}
打开App,阅读手记