Count number of palindrome words in given sentance

write a java program which counts number of words which are palindrome in nature. A string is said to be palindrome if the reverse of the string is same as string. for example : “abba” is palindrome, but “abbc” is not a palindrome.

Question

Write a program which finds count of number of palindromic words present in given string.

Note: A string is said to be palindrome if the reverse of the string is same as string. for example : “abba” is palindrome, but “abbc” is not a palindrome.

Input Specification:

input1: string

input2: length of the string

Output Specification:

Print the number of palindromic words in given string

Example 1:

input1: this is level 107

input2:17

Output: 1

Explanation:

The reverse of the word “level” is “level”, Hence, the word is a palindrome. As the string contains only one palindrome, so the output is 1.

palindromic coding problem
palindromic coding problem

Example 2:

input1: hello world

input2: 11

output: 0

Explanation: As the given string doesn’t contain any palindrome, so the output is 0 (Zero)

Algorithm to solve

  1. Take the input from user that is String and length of the string.
  2. convert the given string to array of string elements, using split method at spaces.
  3. using for loop start iterating through all the words.
  4. select the first word and using a for loop in reverse order start adding each character from given word to new word.
  5. once the 4th step is completed we will be having a new word (reversed).
  6. now just compare reversed word and original word with the help of equals method.
  7. if the equals method returns true the it’s a palindrome otherwise it’s not .
  8. so keep one count which will increase each time a palindrome is found.
  9. that’s it you just solved one off campus coding problem.

JAVA CODE

package arrayPrograms;
import java.util.*;

class Problem16 {
	public static void main(String[] args) {
		
		// ******** coded by VRASHIKESH PATIL *******// 
		
		String s1="level madam mam ";
		String[] array1=s1.split(" ");
		int count=0;
		
		for(int i=0;i<array1.length;i++) {
			
			String s2="";
			
			for(int j=(array1[i].length())-1;j>=0;j--) {
				
				s2=s2+array1[i].charAt(j);
			}
			if(array1[i].equalsIgnoreCase(s2)) {
				count++;
			}
		}
		
		System.out.println(count);		
		
		}
	}


Watch complete step by step explanation for above code

Similar off campus coding problems

Hacker Earth Coding Question with Solution

Saddle points in 2D array off campus problem solved

SHL off campus coding question solved

Accenture off campus coding question

1 thought on “Count number of palindrome words in given sentance”

  1. Pingback: Reducing Dishes coding Complete solution - Is It Actually

Leave a Comment

Your email address will not be published. Required fields are marked *