下面的函数应该检查输入参数是否是回文,并返回true / false。
我知道代码中有错误,应该是:int i = text.size()-1;
问题:如果我不添加“ -1”并打印出text和textR,它们都将是“女士”,据我理解,当我检查(text == textR)时,它应该是真正。但是,它确实返回false
。
有人可以解释一下我在想什么吗?
我知道这与string.size()
和字符串内容不是同一件事有关,并且字符串索引以0开头...我仍然不完全了解为什么text!= textR。
#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()]
是不可打印的'\0'
(空字符)。
所以TextR
是"\0madam"
,而不是预期的"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;
}