[英]function not returning the expected output
我写了一个简单的函数,它接受一个字符串,然后它反转字符串并检查字符串是否是回文,换句话说,如果字符串是对称的,如果是,则返回 true 否则返回 false
程序运行时没有任何错误,但每次调用该函数时都会返回三个零,每个零
#include <iostream>
// Define is_palindrome() here:
bool is_palindrome(std::string text ) {
//std::cout << text << std::endl;
std::string rev_text = ""; // declare a string var to save the reversed word
// reverse the number with a loop
for (int i =text.size(); i >= 0; i--) {
rev_text += text[i];
}
std::cout << text << " " << rev_text << std::endl;
// check if the reversed number is equal to the origianl provided
if (rev_text == text) {
return true;
}
else if ( rev_text != text ) {
return false;
}
}
int main() {
std::cout << is_palindrome("10101") << "\n";
std::cout << is_palindrome("002200") << "\n";
std::cout << is_palindrome("5620265") << "\n";
}
for (int i =text.size(); i >= 0; i--) {
rev_text += text[i];
}
这个循环以i == text.size()
,这意味着您在第一次迭代中访问text[text.size()]
。 这是字符串的最后一个,因此总是返回'\\0'
。
您将其作为第一个元素添加到rev_text
。 所以结果包含了这个不在原始字符中的额外字符。
为了解决这个问题,我建议你使用迭代器:
for(auto it = text.rbegin(); it != text.rend(); it++) {
rev_text += *it;
}
rbegin()
和rend()
为您提供反向遍历向量的迭代器。
或者使用<algorithm>
更简单:
auto rev_text = text;
std::reverse(rev_text.begin(), rev_text.end());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.