Java String Compareto示例
时间:2020-02-23 14:35:12 来源:igfitidea点击:
String的Compareto方法将两个字符串进行了比较。
两个字符串都转换为Unicode值,然后进行比较。
如果我们调用str1.compareto(str2)
然后,如果str1大于str2 返回正数:
0:str1等于str2
负数:str1小于str2
Java String Compareto示例
package org.igi.theitroad;
public class StringCompareToExampleMain {
public static void main(String[] args) {
String str1="theitroad";
String str2="hello";
String str3="world";
String str4="theitroad";
String str5="theitroad";
System.out.println("comparing theitroad with hello : "+str1.compareTo(str2));
System.out.println("comparing hello with world : "+str2.compareTo(str3));
System.out.println("comparing theitroad with theitroad : "+str1.compareTo(str4));
System.out.println("comparing theitroad with theitroad : "+str1.compareTo(str5));
}
}
运行上面的程序时,我们将得到以下输出:
comparing theitroad with hello : 2 comparing hello with world : -15 comparing theitroad with theitroad : 0 comparing theitroad with theitroad : 32

