Write a program to accept a sentence and convert all the words in to palindrome words,the words that are already palindrome will remain same. Palindrome words are spelled same from both sides. Mom, dad, Malayalam are few examples of palindrome words.

import java.util.*;
class MakePalin
{
    public static String toPalin(String s)//to convert a word in to palindrome word and return 
    {
        String temp="";
        int len= s.length();
        for (int  i=len-1;i>=0;i--)
        {
            char ch= s.charAt(i); 
            temp+=ch;
        }
        if (temp.equals(s))//if the word is palindrome return as it is
            return s;
        else
        {
            String temp1="";
            for (int  i=len-2;i>=0;i--)
            {
                char ch= s.charAt(i); 
                temp1+=ch;
            }
            s+=temp1;
            return s;
        }
    }
    public static void main()
    {
        Scanner sc= new Scanner (System.in);
        System.out.println("Enter a sentence");
        String str= sc.nextLine();
        StringTokenizer stz= new StringTokenizer(str);
        System.out.println("The sentence with all the palindromic words is");
        while (stz.hasMoreTokens())     //To extract the words
        {
            String tmp= stz.nextToken();
            System.out.print(toPalin(tmp)+ " ");

        }
    }
}

Output:
Enter a sentence
The water level is rising
The sentence with all the palindromic words is
ThehT wateretaw level isi risingnisir

SHARE
Previous articleRecursion
Next articleArray in JAVA

LEAVE A REPLY

Please enter your comment!
Please enter your name here