关于简单C++函数(is_palindrome)的逻辑的问题

Question about the logic of a simple C++ function (is_palindrome)

本文关键字:palindrome 问题 函数 于简单 简单 C++ is      更新时间:2023-10-16

下面的函数应该检查输入参数是否是回文并返回真/假。

我知道代码中有一个错误,它应该是:int i = text.size()- 1;

问题:如果我不添加"-1"并打印出文本和文本R,它们都是"女士",在我的理解中,当我检查(文本==textR)时,它应该是真的。然而,它确实返回false

有人可以解释一下我错过了什么吗?

我知道这与string.size()和字符串内容不是一回事有关,并且字符串索引以 0 开头......我仍然不完全明白为什么文本 != 文本R。

#include <iostream>
#include <bits/stdc++.h> 
// Define is_palindrome() here:
bool is_palindrome(std::string text) {
// create an empty string to store a reversed version of text 
std::string textR;
// iterating backward over text and adding each character to textR
for (int i = text.size(); i >= 0; i--) {
textR.push_back(text[i]);
}
std::cout << text << std::endl;
std::cout << textR << std::endl;
// check if the reversed text is the same as text; return true or false
if (text == textR) {
return true;
} else {
return false;
}
}
int main() {
std::cout << is_palindrome("madam") << "n";
}

text[text.size()]是不可打印的''(NUL 字符)。

所以TextR"madam"而不是预期的"madam".

答案被给出并接受。好。

此外,我想给出此功能或多或少标准解决方案的答案。

这是一个典型的一行:

#include <iostream>
#include <string>
bool is_palindrome(const std::string& s) { return s == std::string(s.crbegin(), s.crend()); };
int main()
{
std::cout << "Is HannaH a palindrome?: " << is_palindrome("HannaH") << "n";
return 0;
}