21xrx.com
2024-03-29 21:52:36 Friday
登录
文章检索 我的文章 写文章
比较两个字符串的Java程序
2021-07-08 17:37:15 深夜i     --     --
J a v a

Java中如何比较两个字符串,即测试它们是否相等? String 类的 compareTo 方法用于测试其两个对象的相等性。 该方法区分大小写,即“java”和“Java”是它的两个不同字符串。 如果您想比较它们而不考虑它们的情况,请使用 compareToIgnoreCase 方法。

 

Java中的字符串比较

import java.util.Scanner;


class CompareStrings
{
   public static void main(String args[])
   {
      String s1, s2;
      Scanner in = new Scanner(System.in);
     
      System.out.println("Enter the first string");
      s1 = in.nextLine();
     
      System.out.println("Enter the second string");
      s2 = in.nextLine();
     
      if (s1.compareTo(s2) > 0)
         System.out.println("The first string is greater than the second.");
      else if (s1.compareTo(s2) < 0)
         System.out.println("The first string is smaller than the second.");
      else  
         System.out.println("Both the strings are equal.");
   }
}


程序输出:

下载比较字符串程序类文件。

字符串“hello”大于“Hello”,因为'h'的ASCII值大于'H'的ASCII值。 要检查两个字符串是否相等,您可以使用 equals 方法,如果它们相等则返回 true。

  
  
下一篇: Java中的接口

评论区

{{item['qq_nickname']}}
()
回复
回复