c++ - C++ 中的回文扫描器
问题描述
我在 C++ 中的回文“扫描仪”有一点问题。
#include <iostream>
#include <string.h>
#include <string>
using namespace std;
void start() {
string eingabe;
string umkehrung;
cout << "Bitte geben Sie das Wort ein, von welchem getestet werden soll, ob es ein Palindrom ist!" << endl;
cin >> eingabe;
eingabe = ' ' + eingabe;
for (int i = eingabe.length(); i >= 0; i--) {
umkehrung = umkehrung + eingabe[i];
}
if (umkehrung == eingabe) {
cout << "Das Wort '" + eingabe + "' ist ein Palindrom!" << endl;
}
else {
cout << "Das Wort '" + eingabe + "' ist kein Palindrom!" << endl;
cout << eingabe << endl;
cout << umkehrung << endl;
}
}
int main() {
start();
return 0;
}
它反转字符串输入(Eingabe--->Umkehrung),然后检查它们是否相同。但不知何故,它总是说它们不一样,即使它们看起来一样(我在这里输出它们:
cout << eingabe << endl;
cout << umkehrung << endl;
解决方案
您甚至不需要费心创建反向字符串;只需使用反向迭代器和std::equal
:
#include <string>
#include <iostream>
#include <algorithm>
void check (const std::string& s) {
auto s_is_a_palindrome = std::equal(s.begin(), s.end(), s.rbegin());
std::cout << '"' << s << "\" is " << (s_is_a_palindrome ? "" : "not ")
<< "a palindrome\n";
}
int main() {
check("hello olleh");
check("hello, world");
}
这个程序确实会产生:
"hello olleh" is a palindrome
"hello, world" is not a palindrome
注意:您可以停止比较半长,即s.begin() + s.length() / 2
应该也可以代替s.end()
. 比较另一半只是反向进行相同的比较。
推荐阅读
- curl - 在本地主机上使用 CURL 的 MAMP
- html - HTML: tag making
content bold without instruction
- python - 由于 OpenCV,将 Flask 应用程序部署到 Heroku 时出错
- javascript - 组件未在反应应用程序中显示
- javascript - 如何创建一个可以运行python的桌面应用程序
- assembly - 输入仅在 turbo 调试器中可用
- c# - CefSharp 浏览器截屏
- javascript - 将库发布到 npm 时是否需要捆绑文件?
- python - 在 Keras 中使用 fasttext 预训练模型作为嵌入层
- java - 在 macOS 上的 java 中创建一个切换按钮,清楚地显示其切换状态,但没有深蓝色渐变