Java程序比较两个字符串

时间:2020-02-23 14:35:06  来源:igfitidea点击:

在本教程中,我们将看到如何在Java中比较两个字符串。
正如我们所知,String实现了可比的接口,可以使用Compareto方法比较Java中的两个字符串。

import java.util.Scanner;
 
public class StringComparator
{
   public static void main(String args[])
   {
      String str1, str2;
      Scanner scan = new Scanner(System.in);
 
      System.out.print("Enter First String : ");
      str1 = scan.nextLine();
 
      System.out.print("Enter Second String : ");
      str2 = scan.nextLine();
 
      if(str1.compareTo(str2) > 0){
         System.out.println("First String is Greater than Second String.");
      }else if(str1.compareTo(str2) < 0){
         System.out.println("First String is Smaller than Second String.");
      }else{
         System.out.println("Both Strings are Equal (i.e. String1 is Equal to String2)");
      }
   }
}

输出:

Enter First String : Java
Enter Second String : Hello
First String is Greater than Second String.