Print all funny words in a string in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a sentence. Our task is to print all strings from the sentence that are funny words.

Funny word is a word that follows the condition - The absolute difference between adjacent characters of the string and its reverse string is equal.

|string[0] - string[1]| = |revstring[0]-revstring[1]|

Let’s take an example to understand the problem −

Input: string = ‘ABRS’
Output: Yes
Reverse string = SRBA
|A-B| = 1 = |S-R|
|B-R| = 16 = |R-B|
|B-A| = 1 = |R-S|

To solve this problem, we have to extract each string from the given sentence. And print if the string is a funny string.

Check for funny string − For this, we will traverse the string from both ends i.e. from start and from the end. And compare the absolute difference between adjacent characters of the string and return false if the difference is not the same.

The below code will implement our logic −


 Live Demo

#include <iostream>
using namespace std;
bool isFunny(string word){
   int i = 1;
   int j = word.length() - 2;
   for (int i = 0; i < word.length(); i++)
      word[i] = tolower(word[i]);
   while (i <= j){
      if (abs(word[i] -
         word[i - 1]) != abs(word[j] -
      word[j + 1]))
      return false;
   return true;
void printFunnyWords(string str){
   str +=" ";
   string word = "";
   for (int i = 0; i < str.length(); i++){
      char ch = str[i];
      if (ch!=' ')
         word += ch;
         if (isFunny(word))
         word = "";
int main(){
   string sentence = "hello, i love malayalam langauge";
   cout<<"All funny words of the string '"<<sentence<<"' are :\n";
   return 0;


All funny words of the string 'hello, i love malayalam langauge' are :
i malayalam
Published on 22-Jan-2020 16:06:27