如何在 Java 中初始化和比較字串?
你可以使用 compareTo() 方法或 equals() 方法或 == 運算子比較字串。以下示例演示如何在 Java 中初始化並比較字串。
示例
即時演示public class StringDemo {
public static void main(String[] args) {
String str1 = "tutorials";
String 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