Tuesday, 28 May 2013

CHECK WHETHER A GIVEN STRING IS PALINDROME OR NOT IN JAVA

A palindromic string is that string which remains same when reversed. Palindromic string can be thought of as a symmetric string.


Here is a program in java that takes a string form the console and then checks whether this string is palindrome or not.

Source code :-
/*******************************************************************************/

/*PROGRAM TO CHECK WHETHER THE STRING INPUTTED
 * BY THE USER IS PALINDROME OR NOT...
 */
import java.util.Scanner;

public class Palindrome_check {

public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println("ENTER A STRING");
String str=s.nextLine();

char arr[]=new char[str.length()];
/* arr is the array that stores reverse of the string */
int j=0;

/*storing the reverse of str in arr */
for(int i=str.length()-1;i>=0;i--)
{
arr[j]=str.charAt(i);
j++;
}

int flag=1;

/*checking whether the reverse of string and the
* original string are identical or not
*/
for(int i=0;i<str.length();i++)
{
if(str.charAt(i)!=arr[i])
{
flag=0;
break;
/*even if a single character mismatches then break */
}
}

if(flag==1)
System.out.println("IS A PALINDROME");
else
System.out.println("IS NOT A PALINDROME");
}
}
/********************************************************************************/
Output :-
ENTER A STRING
abcde fggf edcba
IS A PALINDROME

No comments:

Post a Comment