用 Java 比较两个字符串的字典顺序。
String 类的 compareTo() 方法。此方法按字典顺序比较两个字符串。比较基于字符串中每个字符的 Unicode 值。由此 String 对象表示的字符序列将与由参数字符串表示的字符序列进行字典顺序比较。此方法返回
- 如果当前 String 对象在字典顺序上位于参数字符串之前,则返回负整数。
- 如果当前 String 对象在字典顺序上位于参数字符串之后,则返回正整数
- 如果字符串相等,则返回 true。
示例
import java.lang.*;
public class StringDemo {
public static void main(String[] args) {
String str1 = "tutorials", str2 = "point";
// comparing str1 and str2
int retval = str1.compareTo(str2);
// prints the return value of the comparison
if (retval < 0) {
System.out.println("str1 is greater than str2");
} else if (retval == 0) {
System.out.println("str1 is equal to str2");
} else {
System.out.println("str1 is less than str2");
}
}
}输出
str1 is less than str2
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP