首页 > 解决方案 > 如何使回文代码不担心(userInput)字间距

问题描述

如标题中所述,我的代码在尝试读取单词之间的空格时遇到问题,例如“从不奇数或偶数”返回为“从不奇数或偶数不是回文”,但它应该说“从不奇怪甚至是回文”。下面我将提供我当前的代码和评分结果以及我似乎无法修复的数字。

#include <iostream>
#include <string>
#include <cctype>
using namespace std;

int main() {
string userInput;
int startInput;
bool isPalindrome = true;

getline (cin, userInput);

startInput = userInput.length();

for (int i = 0; i<(startInput/2); i++){
if (userInput[i] != userInput[(startInput -1) -i])
isPalindrome = false; 
}
if (isPalindrome == true){
cout << userInput << " is a palindrome" << endl;
}
else {
cout << userInput << " is not a palindrome" <<endl;
}

return 0;
}

3:输入:从不奇数或偶数您的输出:从不奇数或偶数不是回文预期输出:从不奇数或偶数是回文

5:输入:dr sorry 你的输出:dr sorry 不是回文 预期输出:dr sorry 是回文

7:输入:no lemon no melon 你的输出:no lemon no melon 不是回文 预期的输出:no lemon no melon 是回文

标签: c++

解决方案


首先,从字符串中删除空格,这可以通过利用std::remove_if在 C++ 中的单个函数调用来完成。

接下来,将删除空格的字符串与字符串的反转版本进行比较。通过使用反向迭代器创建字符串的另一种衬里:

所以让我们分解一下:

1)从字符串中删除空格:

#include <algorithm>
#include <string>
#include <cctype>
//...
std::string s;
//...
s.erase(std::remove_if(s.begin(), s.end(), ::isspace), s.end());

2)构建字符串的反转版本:

   std::string s;
   // ... 
   std::string sreversed == std::string(s.rbegin(), s.rend());

3)把这一切放在一个整洁的功能:

#include <algorithm>
#include <string>
#include <iostream>
#include <cctype>

bool isPalindrome(std::string s)
{
   // erase the spaces
   s.erase(std::remove_if(s.begin(), s.end(), ::isspace), s.end());

   // compare original string with reversed string and return result
   return s == std::string(s.rbegin(), s.rend());
}

int main()
{
   std::string test = "never odd or even";
   bool result = isPalindrome(test);
   std::cout << "\"" << test << "\" is" << (result?" ":" not ") << "a palindrome";
}

输出:

"never odd or even" is a palindrome

推荐阅读