下面的示例通过使用字符串类的str compareTo(字符串),str compareToIgnoreCase(String)和str compareTo(对象字符串)比较两个字符串,并返回比较字符串的第一个奇数字符的ascii差。
public class StringCompareEmp{
public static void main(String args[]) {
String str = "Hello World";
String anotherString = "hello world";
Object objStr = str;
System.out.println( str.compareTo(anotherString) );
System.out.println( str.compareToIgnoreCase(anotherString) );
System.out.println( str.compareTo(objStr.toString()));
}
}上面的代码示例将产生以下结果。
-32 0 0
equals()此方法将此字符串与指定对象进行比较。当且仅当参数不为null并且是一个String对象,表示与此对象相同的字符序列时,结果为true。
public class StringCompareequl{
public static void main(String []args) {
String s1 = "nhooo";
String s2 = "nhooo";
String s3 = new String ("nhooo.com");
System.out.println(s1.equals(s2));
System.out.println(s2.equals(s3));
}
}上面的代码示例将产生以下结果。
true false
public class StringCompareequl{
public static void main(String []args) {
String s1 = "nhooo";
String s2 = "nhooo";
String s3 = new String ("nhooo.com");
System.out.println(s1 == s2);
System.out.println(s2 == s3);
}
}上面的代码示例将产生以下结果。
true false