java中如何比較字符串?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。
Java為我們提供了compareTo、“==”、equals對字符串進行比較,下面介紹一下他們的區別。
示例一:compareTo比較數據的大小
compareTo(string) compareToIgnoreCase(String) compareTo(object string)
該示例通過使用上面的函數比較兩個字符串,并返回一個int類型。若字符串等于參數字符串、則返回0,字符串小于參數字符串、則返回值小于0,字符串大于參數字符串、返回值大于0。
判斷字符串大小的依據是根據他們在字典中的順序決定的。
package com.de.test;
/**
* Java字符串比較大小
*/
public class StringA {
public static void main(String[] args){
String str = "String";
String anotherStr = "string";
Object objstr = str;
System.out.println(str.compareTo(anotherStr));
System.out.println(str.compareToIgnoreCase(anotherStr));
System.out.println(str.compareTo(objstr.toString()));
}
}執行上面代碼產生下面結果
-32 0 0
示例二:使用equals(),“==”方式比較字符串
使用equals()和==,區別在于equals比較的是內容是否相等、==比較的是引用的變量地址是否相等。
package com.de.test;
public class StringA {
public static void main(String[] args){
String s1 = "hello";
String s2 = "hello";
String s3 = new String("hello");
String s4 = new String("hello");
System.out.println("s1:" + s1);
System.out.println("s2:" + s2);
System.out.println("s3:" + s3);
System.out.println("s4:" + s4);
System.out.println("----------比較內容是否相等---------------");
System.out.println(s1.equals(s2));
System.out.println(s2.equals(s3));
System.out.println(s3.equals(s4));
System.out.println("----------比較引用地址是否相等---------------");
System.out.println(s1 == s2);
System.out.println(s2 == s3);
System.out.println(s3 == s4);
}
}執行上面代碼產生下面結果
s1:hello s2:hello s3:hello s4:hello ----------比較內容是否相等--------------- true true true ----------比較引用地址是否相等--------------- true false false
看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業資訊頻道,感謝您對億速云的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。