Java函数编程指南:如何判断两个字符串是否相等?
在Java中,可以使用equals()方法来判断两个字符串是否相等。但是,需要注意的是,不能使用“==”运算符来比较两个字符串是否相等。因为“==”比较的是对象的引用地址,而不是对象本身的值。
下面介绍几种比较字符串相等的方法:
1. equals()方法
使用equals()方法比较字符串相等是最基本的方法。该方法比较的是字符串对象的内容是否相等。例如:
String str1 = "hello";
String str2 = "world";
String str3 = "hello";
String str4 = new String("hello");
System.out.println(str1.equals(str2)); //false
System.out.println(str1.equals(str3)); //true
System.out.println(str1.equals(str4)); //true
由于str4是使用new关键字创建的新的字符串对象,所以其引用地址和str1是不相同的,但是因为其内容相同,所以使用equals()方法比较是相等的。
2. equalsIgnoreCase()方法
使用equalsIgnoreCase()方法比较字符串相等时,忽略字符串中的大小写。例如:
String str1 = "hello";
String str2 = "Hello";
System.out.println(str1.equalsIgnoreCase(str2)); //true
因为忽略了大小写,所以两个字符串相等。
3. compareTo()方法
compareTo()方法比较的是字符串的字典序大小。如果 个字符串小于第二个字符串,则返回一个负数;如果 个字符串大于第二个字符串,则返回一个正数;如果两个字符串相等,则返回0。例如:
String str1 = "hello";
String str2 = "world";
System.out.println(str1.compareTo(str2)); //-15
由于“h”在字典序中的值小于“w”,所以返回一个负数。
4. contentEquals()方法
contentEquals()方法比较的是字符串对象和另一个字符序列的内容是否相等。例如:
String str1 = "hello";
String str2 = "hel";
System.out.println(str1.contentEquals(str2)); //false
虽然两个字符串对象的值在前面几个字符的内容相同,但是其长度不同,所以比较结果为false。
5. matches()方法
matches()方法用于检查字符串是否匹配一个正则表达式。例如:
String str1 = "hello";
String pattern = ".*l.*";
System.out.println(str1.matches(pattern)); //true
正则表达式“.*l.*”表示字符串中包含“l”的任意位置,因此str1匹配这个正则表达式。
除了上述方法之外,还可以使用String类中的其他方法比较字符串相等,例如indexOf()、lastIndexOf()、startsWith()、endsWith()等。需要根据具体的需求来选择适合的方法。
