我只需要一个函数,对于两个给定的字符串,它将返回负值,正值或零值。在C中,使用strcmp
:
char* a = "Hello";
char* b = "Aargh";
strcmp(a, b); //-1
strcmp(a, a); //0
strcmp(b, a); //1
Java是否有任何简单直观的方法,或者我是否必须使用Comparator
界面?
答案 0 :(得分:16)
Java有任何简单直观的方法吗?
是的,它确实:java.lang.String
实现Comparable<String>
接口,compareTo
功能:
int comparisonResult = a.compareTo(b);
还有一个不区分大小写的版本:
int comparisonResult = a.compareToIgnoreCase(b);
答案 1 :(得分:2)
String.compareTo方法是Java中的方法。
如何使用它:
import java.lang.*;
public class StringDemo {
public static void main(String[] args) {
String str1 = "tutorials", str2 = "point";
// comparing str1 and str2
int retval = str1.compareTo(str2);
// prints the return value of the comparison
if (retval < 0) {
System.out.println("str1 is less than str2");
}
else if (retval == 0) {
System.out.println("str1 is equal to str2");
}
else {
System.out.println("str1 is greater than str2");
}
}
}
输出:
str1 is less than str2
示例摘自:http://www.tutorialspoint.com/java/lang/string_compareto.htm
答案 2 :(得分:1)
compareTo
怎么办?
int value = a.compareTo(b);
答案 3 :(得分:0)
您可以使用compareTo,但如果您想要安全,还应包括空检查:
if (a != null){
result = a.compareTo(b);
} else {
//decide what to do here
}
答案 4 :(得分:0)
如前所述,Java有一个内置的String.compareTo(String anotherString)
方法,您应该检查运行时来源(您应该搜索谷歌 rt.jar )。
但是,这是一个在compareTo
方法上应用相同逻辑的工作示例;
public static int stringCompare(String str1, String str2) {
char[] charArray1 = str1.toCharArray();
char[] charArray2 = str2.toCharArray();
int lim = Math.min(charArray1.length, charArray2.length);
int k = 0;
while (k < lim) {
if (charArray1[k] != charArray2[k]) {
return charArray1[k] - charArray2[k];
}
k++;
}
return charArray1.length - charArray2.length;
}
public class StringCmp1 {
public static void main(String[] args) {
String str1 = "aa";
String str2 = "ad";
System.out.println("Comparison of '" + str1 + "' and '" + str2 + "'");
System.out.println("Custom Method : " + str1.compareTo(str2));
System.out.println("Built-in Method : " + stringCompare(str2, str1));
System.out.println("\nComparison of '" + str2 + "' and '" + str1 + "'");
System.out.println("Custom Method : " + str2.compareTo(str1));
System.out.println("Built-in Method : " + stringCompare(str1, str2));
}
public static int stringCompare(String str1, String str2) {
char[] charArray1 = str1.toCharArray();
char[] charArray2 = str2.toCharArray();
int lim = Math.min(charArray1.length, charArray2.length);
int k = 0;
while (k < lim) {
if (charArray1[k] != charArray2[k]) {
return charArray1[k] - charArray2[k];
}
k++;
}
return charArray1.length - charArray2.length;
}
}
Comparison of 'aa' and 'ad'
Custom Method : -3
Built-in Method : 3
Comparison of 'ad' and 'aa'
Custom Method : 3
Built-in Method : -3