Java字符串compareToIgnoreCase()方法与示例
字符串compareToIgnoreCase()方法
compareToIgnoreCase()是Java中的String方法,它通过忽略大小写的敏感性来比较两个字符串。
如果两个字符串相等(不考虑大小写敏感性),则返回0,否则,根据第一个不同的字符差异返回小于0或大于0的值。
语法:
int string1.compareToIgnoreCase(string2);
在这里,string1和string2是要比较的字符串,它返回一个整数值,该值是0,小于0或大于0。
示例
Input:
str1 = "Hello world!"
str2 = "Hello world!"
Output:
0
Input:
str1 = "Hello world!"
str2 = "HELLO WORLD!"
Output:
0
Input:
str1 = "Hello world!"
str2 = "Hi guys!!!"
Output:
-4Java代码使用String.compareToIgnoreCase()方法比较字符串
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 and str2 = " + str1.compareToIgnoreCase(str2));
System.out.println("str1 and str3 = " + str1.compareToIgnoreCase(str3));
System.out.println("str2 and str3 = " + str2.compareToIgnoreCase(str3));
//检查条件
if(str1.compareToIgnoreCase(str2)==0){
System.out.println("str1 is equal to str2");
}
else{
System.out.println("str1 is not equal to str2");
}
if(str1.compareToIgnoreCase(str3)==0){
System.out.println("str1 is equal to str3");
}
else{
System.out.println("str1 is not equal to str3");
}
if(str2.compareToIgnoreCase(str3)==0){
System.out.println("str2 is equal to str3");
}
else{
System.out.println("str2 is not equal to str3");
}
}
}输出结果
str1.compareToIgnoreCase(str2) = 0 str1.compareToIgnoreCase(str3) = 0 str2.compareToIgnoreCase(str3) = 0 str1 is equal to str2 str1 is equal to str3 str2 is equal to str3
public class Main
{
public static void main(String[] args) {
String str1 = "Hello world!";
String str2 = "Hi guys!!!";
if(str1.compareToIgnoreCase(str2)==0){
System.out.println("str1 is equal to str2");
}
else{
System.out.println("str1 is not equal to str2");
}
}
}输出结果
str1 is not equal to str2
热门推荐
3 祝福语简短的微信
10 幼儿祝福语大全简短贺卡
11 感谢教官文案祝福语简短
12 鼠年同事祝福语简短创意
13 元旦祝福语 简短独特群发
14 妈咪跟我生日祝福语简短
15 给儿子新婚祝福语简短
16 伴娘祝福语长文案简短
17 恭喜高考完祝福语简短
18 生日祝福语送老公简短