使用 compareTo() 方法比较字符串的 Java 程序
compareTo(obj) 方法将此字符串与另一个对象进行比较。如果参数是一个与该字符串从词法角度相同的字符串,则返回 0 ;如果参数是一个与该字符串从词法角度较大的字符串,则返回一个小于 0 的值;如果参数是一个与该字符串从词法角度较小的字符串,则返回一个大于 0 的值。
我们有以下两个字符串 −
String str1 = "tom"; String str2 = "tim";
让我们对它们进行所有返回值的检查。
if(str1.compareTo(str2) > 0) { System.out.println("First string is greater!"); } if(str1.compareTo(str2) == 0) { System.out.println("First string is equal to Second string!"); } if(str1.compareTo(str2) < 0) { System.out.println("Second string is greater!"); }
以下是最终的示例。
示例
public class Demo { public static void main(String[] args) { String str1 = "tom"; String str2 = "tim"; if(str1.compareTo(str2) > 0) { System.out.println("First string is greater!"); } if(str1.compareTo(str2) == 0) { System.out.println("First string is equal to Second string!"); } if(str1.compareTo(str2) < 0) { System.out.println("Second string is greater!"); } } }
输出
First string is greater!
让我们看另一个示例。
示例
public class Demo { public static void main(String[] args) { String one = "This is demo text!"; String two = new String("This text is for demo!"); String three = new String("This is demo line!"); String four = new String("The line is demo!"); int res = one.compareTo( two ); System.out.println(res); res = one.compareTo( three ); System.out.println(res); res = one.compareTo( four ); System.out.println(res); } }
输出
-11 8 4
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP