我可以用什么方法在 Java 中比较字符串?举例说明
我们可以使用 compareTo() 方法和 == 运算符在 Java 中比较字符串。
comapareTo() 方法 − compareTo() 方法按字典顺序比较两个字符串。比较基于字符串中每个字符的 Unicode 值。将此 String 对象表示的字符序列按字典顺序与其指定对象表示的字符序列进行比较。
== 运算符 − 您可以使用 == 运算符比较两个字符串。但是,它比较给定变量的引用,而不是值。
String 类中的 equals() 方法接受一个 String 作为参数,并将当前字符串与指定对象进行比较。仅当参数不为 null 且是表示与该对象相同的字符序列的 String 对象时,结果才为 true
示例
public class Example {
public static void main(String[] args) {
String str1 = "tutorials", str2 = "point";
int retval = str1.compareTo(str2);
Boolean bool = str1.equals(str2);
System.out.println(bool);
System.out.println(str1==str2);
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");
}
}
}输出
false false str1 is less than str2
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP