Java 字符串比较,==、equals、matches、compareTo() 的区别。


equals() 方法将此字符串与指定对象进行比较。只有在参数不为 null,并且是表示此对象与相同字符序列的字符串对象时,结果才为 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

您还可以使用 == 运算符比较两个字符串。但是,它比较的是给定变量的引用,而不是值。

Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

示例

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


更新日期: 2020 年 2 月 26 日

612 次浏览

开启你的 职业

完成课程获得认证

开始
广告