C++ 在回文验证中忽略标点、空格和大写字母
到目前为止,我的程序提示用户输入一个字符串,然后从头到尾和向后读取,并比较两个结果。显然,如果他们相等,这是一个回文,如果不是-它不是C++ 在回文验证中忽略标点、空格和大写字母,c++,C++,到目前为止,我的程序提示用户输入一个字符串,然后从头到尾和向后读取,并比较两个结果。显然,如果他们相等,这是一个回文,如果不是-它不是 #include <iostream> #include <stdio.h> using namespace std; int main(){ string input; cout << "Enter a string: "; cin >> input; if (input
#include <iostream>
#include <stdio.h>
using namespace std;
int main(){
string input;
cout << "Enter a string: ";
cin >> input;
if (input == string(input.rbegin(), input.rend())) {
cout << "Yes";
} else {
cout << "No";
}
return 0;
}
#包括
#包括
使用名称空间std;
int main(){
字符串输入;
cout>输入;
if(input==string(input.rbegin(),input.rend()){
不能先处理输入:
#include <algorithm>
#include <boost/algorithm/string/case_conv.hpp>
#include <cctype>
input.erase(
std::remove_if(input.begin(), input.end(),
[] (char c) { return std::isspace(c) || std::ispunct(c); }),
input.end()
);
boost::algorithm::to_lower(input);
#包括
#包括
#包括
输入。删除(
std::如果(input.begin(),input.end(),则删除,
[](char c){return std::isspace(c)| | std::ispunt(c);}),
input.end()
);
boost::algorithm::to_lower(输入);
只需先处理输入:
#include <algorithm>
#include <boost/algorithm/string/case_conv.hpp>
#include <cctype>
input.erase(
std::remove_if(input.begin(), input.end(),
[] (char c) { return std::isspace(c) || std::ispunct(c); }),
input.end()
);
boost::algorithm::to_lower(input);
#包括
#包括
#包括
输入。删除(
std::如果(input.begin(),input.end(),则删除,
[](char c){return std::isspace(c)| | std::ispunt(c);}),
input.end()
);
boost::algorithm::to_lower(输入);
您需要预处理输入字符串以去除非字母字符,并使所有字母字符大小写相同。非主题,但是否相等(input.begin()、input.end()、input.rend())
避免生成临时字符串?@dwvaxaz在我看来,更改原始字符串不是一个好主意。我认为您不应该更改原始字符串。您只需要说明它是否是回文。您需要对输入字符串进行预处理,以去除非字母字符,并使所有字母字符大小写相同。Off主题,但是equal(input.begin()、input.end()、input.rend())
如何避免生成临时字符串?@dwvaxaz在我看来,更改原始字符串不是一个好主意。我认为您不应该更改原始字符串。您只需要说明它是否是回文。