Java中字符串比较的多种方法及实现
在Java中,字符串比较是一个常见的操作。下面介绍几种常用的字符串比较方法。
1. equals()方法
equals()方法是Java中最基本和最常用的字符串比较方法。该方法比较两个字符串是否相等,如果相等返回true,否则返回false。
示例代码:
String str1 = "hello";
String str2 = "world";
if(str1.equals(str2)){
System.out.println("两个字符串相等");
}else{
System.out.println("两个字符串不相等");
}
输出结果:
两个字符串不相等
2. equalsIgnoreCase()方法
equalsIgnoreCase()方法也是比较两个字符串是否相等,但是不区分大小写。
示例代码:
String str1 = "Hello";
String str2 = "HELLO";
if(str1.equalsIgnoreCase(str2)){
System.out.println("两个字符串相等");
}else{
System.out.println("两个字符串不相等");
}
输出结果:
两个字符串相等
3. compareTo()方法
compareTo()方法比较两个字符串的大小关系,如果调用该方法的字符串大于参数字符串,则返回正整数,如果小于参数字符串,则返回负整数,如果两个字符串相等,则返回0。
示例代码:
String str1 = "abc";
String str2 = "def";
int result = str1.compareTo(str2);
if(result > 0){
System.out.println("str1大于str2");
}else if(result < 0){
System.out.println("str1小于str2");
}else{
System.out.println("两个字符串相等");
}
输出结果:
str1小于str2
4. startsWith()方法
startsWith()方法判断一个字符串是否以指定的前缀开头,如果是返回true,否则返回false。
示例代码:
String str1 = "hello";
if(str1.startsWith("he")){
System.out.println("以he开头");
}else{
System.out.println("不是以he开头");
}
输出结果:
以he开头
5. endsWith()方法
endsWith()方法判断一个字符串是否以指定的后缀结尾,如果是返回true,否则返回false。
示例代码:
String str1 = "hello";
if(str1.endsWith("lo")){
System.out.println("以lo结尾");
}else{
System.out.println("不是以lo结尾");
}
输出结果:
以lo结尾
6. contains()方法
contains()方法判断一个字符串是否包含指定的子字符串,如果包含返回true,否则返回false。
示例代码:
String str1 = "hello";
if(str1.contains("he")){
System.out.println("包含he");
}else{
System.out.println("不包含he");
}
输出结果:
包含he
7. matches()方法
matches()方法判断一个字符串是否匹配指定的正则表达式,如果匹配返回true,否则返回false。
示例代码:
String str1 = "123";
if(str1.matches("\\d+")){
System.out.println("是数字");
}else{
System.out.println("不是数字");
}
输出结果:
是数字
以上是几种比较常见的字符串比较方法,开发中可根据实际需求选择合适的方法。
