gpt4 book ai didi

c++ - 如何忽略空格和标点符号?

转载 作者:行者123 更新时间:2023-11-27 23:50:26 25 4
gpt4 key购买 nike

我写了一个回文检查器函数,它在大多数情况下都有效,但如果空格或标点符号不在字符串的中间,它就说它不是回文。

第一次测试:

Enter string to test for palindrome:

hannah

string is a palindrome.

第二次测试:

Enter string to test for palindrome:

han nah

string is a palindrome.

第三个测试:

Enter string to test for palindrome:

hann.ah

string is not a palindrome.

第四次测试:

Enter string to test for palindrome:

han.nah

string is a palindrome.

我想知道是否有一种方法可以同时忽略空格和标点符号,以便将 h.annahhann ah 视为回文?

这是我的代码:

void isPalindrome (string s){  
if(equal(s.begin(), s.begin() + s.size()/2, s.rbegin()) )
cout << "string is a palindrome. " << endl;
else
cout << "string is not a palindrome. " << endl;
}

int main(){
string test1;
cout << "Enter string to test for palindrome: " << endl;
getline(cin, test1);

isPalindrome(test1);

string test2;
cout << "Enter string to test for palindrome: " << endl;
getline(cin, test2);

isPalindrome(test2);

string test3;
cout << "Enter string to test for palindrome: " << endl;
getline(cin, test3);

isPalindrome(test3);

return 0;
}

最佳答案

在回文检查之前对字符串应用过滤器。

这是一种方法。

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

void isPalindrome (std::string s){
if(equal(s.begin(), s.begin() + s.size()/2, s.rbegin()) )
std::cout << "string is a palindrome. " << std::endl;
else
std::cout << "string is not a palindrome. " << std::endl;
}

std::string remove_rubbish(std::string s)
{
auto is_rubbish = [](char c)
{
return std::ispunct(c) || std::isspace(c);
};

s.erase(std::remove_if(s.begin(),
s.end(),
is_rubbish),
s.end());

return s;
}

int main(){
auto s= std::string("ha-n.n?a h");
isPalindrome(remove_rubbish(s));

return 0;
}

关于c++ - 如何忽略空格和标点符号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46834492/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com