如何使Palindrome代码不必担心(用户input)单词间距



,如标题中所述,我在代码上试图在单词之间读取空间,例如"从不奇怪甚至"返回,因为"从不奇怪,甚至不是一个回文",但它应该说"从来没有奇怪甚至是一个al骨"。在下面,我将提供我当前的代码和分级结果以及我似乎无法修复的数字。

#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尴尬不是回文预期输出:Dr awkward是一个回文

7:输入:没有柠檬没有瓜您的输出:没有柠檬没有瓜不是回文预期输出:无柠檬没有瓜是walindrome

首先,从字符串中删除空格,可以通过使用std :: remove_if。

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

所以让我们分解一下:

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

为什么不在测试之前从字符串中删除空格,如果是alsindrome?如您现在的使用时,使用getline((,然后从输入中删除所有空格,然后进行palindrome测试。

此链接可能有助于删除空间的方法:https://www.geeksforgeeks.org/remove-spaces-from-a-a-given-string/

旁注:将布尔值与true进行比较,就像您与if (isPalindrome == true)一样。您只能使用if (isPalindrome)

相关内容

最新更新