How to print the longest palindrome words in a string with C++

2 Answers

0 votes
#include <iostream>
#include <sstream>
  
void PrintLongestPalindromeWord(std::string str) {
    std::istringstream ss(str);
    std::string word; 
    size_t max = 0;
    std::string maxword;
    
    while (ss >> word) {
        std::string rev_word(word.rbegin(), word.rend());
        int wordlen = word.size();
        if (word == rev_word && wordlen >= 3) {
            if (wordlen > max) {
                max = wordlen;
                maxword = word;
            }
        }
    }
    
    std::cout << maxword << "\n";
}
    
  
int main()
{
    std::string str = "c madam c++ civic java rotator pytyp dart php";
      
    PrintLongestPalindromeWord(str);
}
 
  
  
  
/*
run:
          
rotator
     
*/

 



answered Dec 29, 2023 by avibootz
0 votes
#include <iostream>
#include <sstream>
   
std::string  GetTheLongestPalindromeWord(std::string str) {
    std::istringstream ss(str);
    std::string word; 
    size_t max = 0;
    std::string maxword;
     
    while (ss >> word) {
        std::string rev_word(word.rbegin(), word.rend());
        int wordlen = word.size();
        if (word == rev_word && wordlen >= 3) {
            if (wordlen > max) {
                max = wordlen;
                maxword = word;
            }
        }
    }
     
    return maxword;
}
     
   
int main()
{
    std::string str = "c madam c++ civic java rotator pytyp dart php";
       
    std::string maxword = GetTheLongestPalindromeWord(str);
    
    std::cout << maxword << "\n";
}
  
   
   
   
/*
run:
           
rotator
      
*/

 



answered Dec 29, 2023 by avibootz
...