下面的函数应该检查输入参数是否是回文,并返回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'
(nul字符),无法打印。
因此TextR
是"\0madam"
而不是预期的"madam"
。
关于c++ - 有关简单C++函数的逻辑的问题(is_palindrome),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60339643/