比较 java 中的两个字符串 - equals() 和 equalsIgnoreCase()
首先想到的是与==但这是完全错误的。当我开始使用 Java 编程时,我用==”比较了两个字符串,它测试对象的相等性,但不是两个字符串两个字符之间的相等性。与 C++ 不同, Java 设计人员在 String 类中创建了方法来简化语言,因为它是面向对象的。比较 String 与 equals
class String 的 equals() 方法测试 java 或变量内容中值的相等,并返回 true 如果两个字符串都包含相同的字符。下面是一个示例:
String s1=str”;equals() 区分大小写(小写或大写):
字符串 s2=str”;
if(s1.equals(s2))
System.out.println(两个字符串相等”);
String s1=str”;在这种情况下,它返回 false.
字符串 s2=STR”;
if(s1.equals(s2))
System.out.println(两个字符串相等”);
Ignore 大写字母,并带有 equalsIgnoreCase()
equalsIgnoreCase() 方法避免将 String 从小写字母传递到大写字母,并将其与 equals() 进行比较,Java 提供了一个 equalsIgnoreCase() 方法,该方法将字符转换为小写字母并比较两个字符串><<。br />
String s1=str”;
字符串 s2=STR”;
if(s1.equalsIgnoreCase(s2))
System.out.println(对忽略大小写的敏感度。两个字符串相等);
Size comparison
String 类具有返回字符串长度的 length() 方法:
if(string1”.length()==string2”.length())
System.out.println(string1 和 string2 大小相等”);
else if(string1”.length()>”string2.length())
System.out.println(”string1 更长);
else
System.out.println(string2 更长”);
equals 和 ==”
equals() 方法测试值的相等性。
new String(test”).equals(new String(test”));//-->true==”运算符测试对象的相等性,这里有一系列需要避免的错误:
String s1=trial”;串联返回 true,因为它是在编译过程中调用的,这与在运行时调用的 substring() 和 replace() 不同,并且将创建一个不等于等式另一侧的新对象><。
字符串 s2=trial”;
//它们是同一个对象
s1==s2;-->false
//它们不是同一个对象
s1 == test”;-->false
//它们引用同一个对象
test” == test”;-->true
//串联被视为单个对象
test” == your”+t”;-->true
//substring() 方法生成一个新对象
test” == 1test”.substring(1);-->false
//replace() 方法生成一个新对象
test” == Test”.replace(T”, t”);-->false