Java String compareTo()方法与示例
字符串compareTo()方法
compareTo()是Java中的String方法,用于比较两个字符串(区分大小写)。
如果两个字符串相等-返回0,否则,根据第一个不同的字符差返回小于0或大于0的值。
语法:
int string1.compareTo(string2);
在这里,string1和string2是要比较的字符串,它返回一个整数值,该值是0,小于0或大于0。
示例
Input:
str1 = "Hello world!"
str2 = "Hello world!"
Output:
0
Input:
str1 = "Hello world!"
str2 = "HELLO WORLD!"
Output:
32Java代码使用String.compareTo()方法比较字符串
public class Main
{
public static void main(String[] args) {
String str1 = "Hello world!";
String str2 = "Hello world!";
String str3 = "HELLO WORLD!";
System.out.println("str1.compareTo(str2) = " + str1.compareTo(str2));
System.out.println("str1.compareTo(str3) = " + str1.compareTo(str3));
System.out.println("str2.compareTo(str3) = " + str2.compareTo(str3));
//检查条件
if(str1.compareTo(str2)==0){
System.out.println("str1 is equal to str2");
}
else{
System.out.println("str1 is not equal to str2");
}
if(str1.compareTo(str3)==0){
System.out.println("str1 is equal to str3");
}
else{
System.out.println("str1 is not equal to str3");
}
if(str2.compareTo(str3)==0){
System.out.println("str2 is equal to str3");
}
else{
System.out.println("str2 is not equal to str3");
}
}
}输出结果
str1.compareTo(str2) = 0 str1.compareTo(str3) = 32 str2.compareTo(str3) = 32 str1 is equal to str2 str1 is not equal to str3 str2 is not equal to str3
热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短