如何在 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

更新於: 30-7-2019

151 次瀏覽

開啟你的 職業生涯

透過完成課程獲取認證

入門
廣告
© . All rights reserved.