简体   繁体   English

C++ 表示回文

[英]C++ indicate Palindrome

I'm pretty new to coding in C++ and need your help.我对 C++ 编码很陌生,需要你的帮助。 In the code below I want to check for Parlindrome and show the reversed text.在下面的代码中,我想检查 Parlindrome 并显示反转文本。 So if I run this code, it displays the right reversed words, but dont return them true if checked for parlindrome.因此,如果我运行此代码,它会显示正确的反向单词,但如果检查 parlindrome,则不会将它们返回 true。

The console shows: madam0 ada0 ecalevol0控制台显示: madam0 ada0 ecalevol0

Why the return is always 0?为什么返回总是0?

Thanks for your help!谢谢你的帮助!

#include <iostream>

// Define is_palindrome() here:

bool is_palindrome(std::string text) {
  std::string text_reversed;

  for(int i = text.length(); i >= 0; i-- ) {
    text_reversed += text[i];
    std::cout << text[i];
  }

  if (text_reversed == text) {
    return true;
  } else {
    return false;
  }
}

int main() {
  
  std::cout << is_palindrome("madam") << "\n";
  std::cout << is_palindrome("ada") << "\n";
  std::cout << is_palindrome("lovelace") << "\n";
}

Your i starts at text.length() , not text.length() - 1 .你的itext.length()开始,而不是text.length() - 1

So, your first text[i] is a null byte (yes, even for std::string , this is guaranteed).所以,你的第一个text[i]是一个空字节(是的,即使对于std::string ,这也是有保证的)。

Thus the first character of text_reversed is a "hidden" character that was not present in text , and the two will never match.因此,第一个字符text_reversed是一个“隐藏”的字符是不存在的text ,两个永远不会匹配。

std::string reversed_string(const std::string& s)
{
    return {s.rbegin(), s.rend()};
}

bool is_palindrome(const std::string& s)
{
    return std::equal(s.begin(), s.begin() + s.size() / 2, s.rbegin());
}

Documentation of std::equal has example of is_palindrome std::equal 的文档有is_palindrome例子

Your biggest problems there are i>=0 and text[i] .你最大的问题是i>=0text[i] It should be i>0 and text[i-1] .它应该是i>0text[i-1]

And please simplify that return statement.并请简化该退货声明。

#include <iostream>

bool is_palindrome(std::string text) {

  std::string text_reversed = "";

  for(int i = text.length(); i > 0; i-- ) {
    text_reversed += text[i-1];
  }
  std::cout << text_reversed <<std::endl;
  std::cout << text <<std::endl;

  return text == text_reversed;
}

int main() {
  std::cout << is_palindrome("madam") << std::endl;
  std::cout << std::endl;
  std::cout << is_palindrome("ada") << std::endl;
  std::cout << std::endl;
  std::cout << is_palindrome("lovelace") << std::endl;
  std::cout << std::endl;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM