日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > java >内容正文

java

Java String compareTo()方法与示例

發(fā)布時(shí)間:2025/3/11 java 20 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Java String compareTo()方法与示例 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

字符串compareTo()方法 (String compareTo() Method)

compareTo() is a String method in Java and it is used to compare two strings (case-sensitive).

compareTo()是Java中的String方法,用于比較兩個(gè)字符串(區(qū)分大小寫)。

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.

如果兩個(gè)字符串相等–返回0 ,否則,根據(jù)第一個(gè)不同的字符差返回小于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是要比較的字符串,它返回一個(gè)整數(shù)值,該值是0,小于0或大于0。

Example:

例:

Input: str1 = "Hello world!"str2 = "Hello world!"Output:0Input: str1 = "Hello world!"str2 = "HELLO WORLD!"Output:32

Java 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

總結(jié)

以上是生活随笔為你收集整理的Java String compareTo()方法与示例的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。