检测是否为回文字符串 C++实现
回文字符串,是一个正读和反读都一样的字符串,比如“level”或者“noon”等等就是回文字符串。
检测原理:定义两个迭代器,一个指向字符串头部,一个是反向迭代器,指向反向头部,再逐字比较。
源代码
#include <iostream>
#include <string>
using namespace std;
bool Test(const string &temp_str) {
auto it_b = temp_str.begin();
auto it_rb = temp_str.rbegin();
auto temp_size = temp_str.size();
for (auto i = 0; i != temp_size / 2; ++i, ++it_b, ++it_rb) {
if (*it_b != *it_rb) {
return false;
}
}
return true;
}
int main() {
string temp_str;
cout << "请输入字符:" << endl;
cin >> temp_str;
if (Test(temp_str)) {
cout << "yes" << endl;
}
else {
cout << "no" << endl;
}
return 0;
}