Gadgets

Showing posts with label reverse string. Show all posts
Showing posts with label reverse string. Show all posts

Monday, 14 December 2015

Check the given string is palindrome or not

Check the given string is palindrome or not:
If we reverse a string that reverse string and original string both are equal then that string is palindrome.
Example:
Original string: java
Reverse string: avaj
Both are not equal so not palindrome.
Original string: madam
Reverse string: madam
Both are equal so palindrome.
length():- length() is final method, it is applicable for String Objects. length() method returns number of characters present in the String.
chatAt() method:-
Returns the char value at the specified index. An index ranges from 0 to length()-1. The first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing.
import java.util.Scanner;
public class PalindromeTest {
    public static void main(String[] arg){
        String name,rev="";
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter Name :");
        name=sc.nextLine();        
        System.out.println("length of the String : "+name.length());
        int i=name.length();//i=string length
        for(int j=i-1;j>=0;j--){
           rev=rev+name.charAt(j);
        }
        System.out.println("reverse string is : "+rev);     
    }
}
/*
Output:-
Enter Name :
java
length of the String : 4
reverse string is : avaj
*/
import java.util.Scanner;
public class PalindromeTest {
    public static void main(String[] arg){
        String name,rev="";
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter Name :");
        name=sc.nextLine();        
        System.out.println("length of the String : "+name.length());
        int i=name.length();//i=string length
        for(int j=i-1;j>=0;j--){
           rev=rev+name.charAt(j);
        }
        System.out.println("reverse string is : "+rev);
        if(name.equals(rev)){
            /* check given string and reverse string are equal or not*/
          System.out.println("palindrome ");  
        }
        else{
            System.out.println("not palindrome ");  
        }
    }
}
/*
Output-1:-
Enter Name :
java
length of the String : 4
reverse string is : avaj
not palindrome 
Output-2:-
Enter Name :
madam
length of the String : 5
reverse string is : madam
palindrome
*/