关于简单C++函数(is_palindrome)的逻辑的问题
Question about the logic of a simple C++ function (is_palindrome)
下面的函数应该检查输入参数是否是回文并返回真/假。
我知道代码中有一个错误,它应该是: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;
}
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 编译包含字符串的代码时遇到问题
- Project Euler问题4的错误解决方案
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 静态数据成员的问题-修复链接错误会导致编译器错误
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 一个关于在C++中重载布尔运算符的问题
- 首要问题的答案让值班员搞错了
- setlocale的C++土耳其字符串问题
- 如何重构类层次结构以避免菱形问题
- 基于boost的程序的静态链接——zlib问题
- C++格式化输出问题
- 使用mongocxx驱动程序时包含头文件问题