Java String compareTo()方法与示例
字符串compareTo()方法 (String compareTo() Method)
compareTo() is a String method in Java and it is used to compare two strings (case-sensitive).
compareTo()是Java中的String方法,用于比較兩個字符串(區分大小寫)。
If both strings are equal – it returns 0, otherwise, it returns a value less than 0 or greater than 0 based on the first dissimilar characters difference.
如果兩個字符串相等–返回0 ,否則,根據第一個不同的字符差返回小于0或大于0的值。
Syntax:
句法:
int string1.compareTo(string2);Here, string1 and string2 are the strings to be compared, and it returns an integer value that is 0, less than 0 or greater than 0.
在這里, string1和string2是要比較的字符串,它返回一個整數值,該值是0,小于0或大于0。
Example:
例:
Input: str1 = "Hello world!"str2 = "Hello world!"Output:0Input: str1 = "Hello world!"str2 = "HELLO WORLD!"Output:32Java code to compare strings using String.compareTo() method
Java代碼使用String.compareTo()方法比較字符串
public class Main {public static void main(String[] args) {String str1 = "Hello world!";String str2 = "Hello world!";String str3 = "HELLO WORLD!";System.out.println("str1.compareTo(str2) = " + str1.compareTo(str2));System.out.println("str1.compareTo(str3) = " + str1.compareTo(str3));System.out.println("str2.compareTo(str3) = " + str2.compareTo(str3));//checking with the conditionif(str1.compareTo(str2)==0){System.out.println("str1 is equal to str2");}else{System.out.println("str1 is not equal to str2");}if(str1.compareTo(str3)==0){System.out.println("str1 is equal to str3");}else{System.out.println("str1 is not equal to str3");} if(str2.compareTo(str3)==0){System.out.println("str2 is equal to str3");}else{System.out.println("str2 is not equal to str3");} } }Output
輸出量
str1.compareTo(str2) = 0 str1.compareTo(str3) = 32 str2.compareTo(str3) = 32 str1 is equal to str2 str1 is not equal to str3 str2 is not equal to str3翻譯自: https://www.includehelp.com/java/string-compareTo-method-with-example.aspx
總結
以上是生活随笔為你收集整理的Java String compareTo()方法与示例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: duration java_Java D
- 下一篇: java中的starts_Java Ma