下面的函数应该检查输入参数是否是回文,并返回true/false。
我知道代码中有一个错误,应该是: int = text.size() - 1;
问题:如果我不添加"-1“并打印出文本和textR,它们都是”夫人“,据我理解,当我检查(文本== textR)时,这应该是真的。不过,它确实返回了false。
有人能解释一下我错过了什么吗?
我知道这与string.size()和字符串内容不是同一回事有关,字符串索引从0开始.我还是不完全明白为什么要发短信!= 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";
}发布于 2020-02-21 13:32:15
text[text.size()]是不可打印的'\0' (nul字符)。
因此,TextR是"\0madam"而不是预期的"madam"。
发布于 2020-02-21 19:30:39
答案是给予并接受的。好的。
此外,我想给出这个函数或多或少的标准解决方案的答案。
这是一个典型的一个班轮:
#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;
}https://stackoverflow.com/questions/60339643
复制相似问题