使用Java中的equals()和compareTo()方法比较字符串
Given strings and we have to compare them using equals() and compareTo() method.
給定字符串,我們必須使用equals()和compareTo()方法進行比較。
Java string equals() method
Java字符串equals()方法
Java string equals() method compares the content of two strings, If all characters are the same, it returns
Java字符串equals()方法比較兩個字符串的內(nèi)容,如果所有字符都相同,則返回
true, else it returns false.
是true ,否則返回false 。
Java string compareTo() method
Java字符串compareTo()方法
Java string compareTo() method is called with a string and another string is supplied as an argument, it compares the strings based on the Unicode values of the characters in the strings. It returns a
使用字符串調(diào)用Java字符串compareTo()方法,并提供另一個字符串作為參數(shù),它根據(jù)字符串中字符的Unicode值比較字符串。 它返回一個
positive number, negative number or 0. If both strings have the same content, it returns 0.
正數(shù) , 負(fù)數(shù)或0 。 如果兩個字符串的內(nèi)容相同,則返回0 。
Java代碼使用equals(),compareTo()和==運算符比較字符串 (Java code to compare the strings using equals(), compareTo() and == operator )
// Comparing Strings with equals() and compareTo() // methods in Javapublic class Main {public static void main(String[] args) {//stringsString str1 = new String("ABC");String str2 = new String("PQR");//comparing strings using equals() methodSystem.out.println(str1.equals(str2));System.out.println(str1.equals(str1));//comparing strings using == operator System.out.println(str1 == str1);System.out.println(str1 == str2);//comparing strings using compareTo() methodSystem.out.println(str1.compareTo(str1));System.out.println(str1.compareTo(str2));} }Output
輸出量
false true true false 0 -15翻譯自: https://www.includehelp.com/java-programs/comparing-strings-with-equals-and-compareto-methods-in-java.aspx
總結(jié)
以上是生活随笔為你收集整理的使用Java中的equals()和compareTo()方法比较字符串的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 字符串 charat_Java | St
- 下一篇: 眼镜框一般多少钱啊?