Java 字串比較,==、equals、matches、compareTo() 的區別。
equals() 方法將此字串與指定的物件進行比較。僅當引數不為 null 且是表示與 this 物件相同字元序列的字串物件時,結果才為 true。
示例
public class Sample{
public static void main(String []args){
String s1 = "tutorialspoint";
String s2 = "tutorialspoint";
String s3 = new String ("Tutorials Point");
System.out.println(s1.equals(s2));
System.out.println(s2.equals(s3));
}
}輸出
true false
你還可以使用 == 運算子比較兩個字串。不過,它比較的是給定變數的引用而不是值。
示例
public class Sample {
public static void main(String []args) {
String s1 = "tutorialspoint";
String s2 = "tutorialspoint";
String s3 = new String ("Tutorials Point");
System.out.println(s1 == s2);
System.out.println(s2 == s3);
}
}輸出
true false
String 類的 matches() 方法會指示此字串是否與給定的正則表示式匹配。str.matches(regex) 形式的此方法的呼叫會產生與正則表示式 Pattern.matches(regex, str) 完全相同的結果。
示例
import java.io.*;
public class Test {
public static void main(String args[]) {
String Str = new String("Welcome to Tutorialspoint.com");
System.out.print("Return Value :" );
System.out.println(Str.matches("(.*)Tutorials(.*)"));
System.out.print("Return Value :" );
System.out.println(Str.matches("Tutorials"));
System.out.print("Return Value :" );
System.out.println(Str.matches("Welcome(.*)"));
}
}輸出
Return Value :true Return Value :false Return Value :true
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP