Một số phương thức so sánh hai chuỗi trong java. (A some method compare two string in Java.)






Bài viết này sẽ cung cấp ví dụ demo các phương thức so sánh chuỗi, từ đây ta có thể nhận biết được sự khác biệt của các phương thức, và có sự áp dụng phù hợp tùy theo từng trường hơp.






JavaComparesTwoString
/**
 * @(#)JavaComparesTwoString.java
 *
 * JavaComparesTwoString application
 *
 * @author developer.bnson@gmail.com
 * @version 1.00 2014/3/15
 */

public class JavaComparesTwoString {
   
    public static void main(String[] args) {
       
      String str_01 = "vn-lives.net";
      String str_02 = "vn-lives.net";
      String str_03 = "VN-LIVES.NET";

      // Java String comparison with the equals method.
      // So sánh chuỗi với phương thức equals.
      if (str_01.equals(str_02)){
       System.out.println("str_01 and str_02 are the same.");
      }

      // Java String comparison with the equalsIgnoreCase method.
      // So sánh chuỗi với phương thức equalsIgnoreCase.
      if (str_01.equalsIgnoreCase(str_03)) {
       System.out.println("str_01 and str_03 match iggnore case.");
      }


      // Java String comparison with the compareTo method.
      // So sánh chuỗi với phương thức compareTo.
      if (str_01.compareTo(str_02) == 0) {
       System.out.println("str_01 and str_02 are the same.");
      }


      // Java String comparison with the compareToIgnoreCase method.
      if ( str_01.compareToIgnoreCase(str_03) == 0) {
       System.out.println("str_01 and str_03 match ignore case.");
      }
     
    }
}

Kết quả chương trình sau khi thực thi sẽ là:

str_01 and str_02 are the same.
str_01 and str_03 match iggnore case.
str_01 and str_02 are the same.
str_01 and str_03 match ignore case.


















No comments:

Post a Comment