Showing posts with label compare. Show all posts
Showing posts with label compare. Show all posts

How to test string for a Palindrome?

Question:
How can you test a string to see if it is a palidrome?

Answer:
By comparing the string with a 2nd string created by the method StringBuilder().reverse().

Code:
import java.util.*;
 
public class  Palidrome {
   public static void main(String[] args) {
 
      Scanner sc = new Scanner(System.in);
 
      System.out.println("Enter exit to quit.");
      while(true){
         System.out.print("Enter a word: ");
         String str = sc.nextLine();
 
         if(str.equals("exit")){
            break;
         }
 
         String reverse = new StringBuilder(str).reverse().toString();
         if (str.toLowerCase().compareTo(reverse.toLowerCase()) == 0) {
           System.out.println(str + " is a palidrome");
         } else {
           System.out.println(str + " is not a palidrome");
         }
      }
      sc.close();
   }
} 

Output:
$ java Palidrome 
Enter exit to quit.
Enter a word: hello
hello is not a palidrome
Enter a word: racecar
racecar is a palidrome
Enter a word: Racecar
Racecar is a palidrome
Enter a word: exit

How do you compare two strings in java?

Question:
How do you compare two string in java?

Code:
public class CompareStrings { 
   public static void main(String[] args) { 
      String str1 = "foo"; 
      String str2 = "foo"; 
      String str3 = "FOO"; 
 
      System.out.println("str1: " + str1); 
      System.out.println("str2: " + str2); 
 
 
      // java String comparison with the equals method
      if ( str1.equals(str2) ){
       System.out.println("str1 and str2 are the same"); 
      }
 
      // java String comparison with the equalsIgnoreCase method
      if ( str1.equalsIgnoreCase(str3)) {
       System.out.println("str1 and str3 match ignooring case"); 
      }
 
 
      // java String comparison with the compareTo method
      if ( str1.compareTo(str2) == 0) {
       System.out.println("str1 and str2 are the same"); 
      }
 
 
      // java String comparison with the compareToIgnoreCase method
      if ( str1.compareToIgnoreCase(str3) == 0) {
       System.out.println("str1 and str3 match ignooring case"); 
      }
 
   }
}

Output:
$ java CompareStrings 
str1: foo
str2: foo
str1 and str2 are the same
str1 and str3 match ignooring case
str1 and str2 are the same
str1 and str3 match ignooring case