Comparing a string that is reversed (palindrome)

I am using the below function and getting the below output. Can someone please explain why.
It prints out that they are equal after the for loop finishes but when compared the logic says they are not equal.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>#include <iostream>
#include <string.h>
bool palindrome;
// Define is_palindrome() here:
bool is_palindrome(std::string text){
std::string backwards = "";
for (int i = text.length();i >= 0; i--){
backwards = backwards + text[i];
std::cout << backwards << std::endl;
}
std::cout << backwards << " and " << text << std::endl;
if (text == backwards){
std::cout << "they are equal" << std::endl;
palindrome = true;
}
else{
std::cout << "they are not equal" << std::endl;
palindrome = false;
}
return palindrome;
}
int main() {
std::cout << is_palindrome("madam") << "n";
}
</code>
<code>#include <iostream> #include <string.h> bool palindrome; // Define is_palindrome() here: bool is_palindrome(std::string text){ std::string backwards = ""; for (int i = text.length();i >= 0; i--){ backwards = backwards + text[i]; std::cout << backwards << std::endl; } std::cout << backwards << " and " << text << std::endl; if (text == backwards){ std::cout << "they are equal" << std::endl; palindrome = true; } else{ std::cout << "they are not equal" << std::endl; palindrome = false; } return palindrome; } int main() { std::cout << is_palindrome("madam") << "n"; } </code>
#include <iostream>
#include <string.h>

 bool palindrome;


// Define is_palindrome() here:

 bool is_palindrome(std::string text){
  std::string backwards = "";
  for (int i = text.length();i >= 0; i--){
  backwards = backwards + text[i];
   std::cout << backwards << std::endl;
  }
  std::cout << backwards << " and " << text << std::endl;
  if (text == backwards){
    std::cout << "they are equal" << std::endl;
    palindrome = true;
  }
  else{
    std::cout << "they are not equal" << std::endl;
    palindrome = false;
  }
  return palindrome;
}

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

OUTPUT

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>
m
ma
mad
mada
madam
madam and madam
they are not equal
0
</code>
<code> m ma mad mada madam madam and madam they are not equal 0 </code>

m
ma
mad
mada
madam
madam and madam
they are not equal
0

New contributor

krogerson2 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

13

Instead of int i = text.length() it should be i = text.length() - 1 because you make an extra loop.

Also, I’ve changed the return state.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>#include <iostream>
#include <string>
bool is_palindrome(std::string text) {
std::string backwards = "";
for (int i = text.length() - 1; i >= 0; i--) {
backwards = backwards + text[i];
}
std::cout << backwards << " and " << text << std::endl;
if (text == backwards) {
std::cout << "they are equal" << std::endl;
return true;
} else {
std::cout << "they are not equal" << std::endl;
return false;
}
}
int main() {
std::cout << is_palindrome("madam") << "n";
}
</code>
<code>#include <iostream> #include <string> bool is_palindrome(std::string text) { std::string backwards = ""; for (int i = text.length() - 1; i >= 0; i--) { backwards = backwards + text[i]; } std::cout << backwards << " and " << text << std::endl; if (text == backwards) { std::cout << "they are equal" << std::endl; return true; } else { std::cout << "they are not equal" << std::endl; return false; } } int main() { std::cout << is_palindrome("madam") << "n"; } </code>
#include <iostream>
#include <string>

bool is_palindrome(std::string text) {
    std::string backwards = "";
    for (int i = text.length() - 1; i >= 0; i--) {
        backwards = backwards + text[i];
    }
    std::cout << backwards << " and " << text << std::endl;
    if (text == backwards) {
        std::cout << "they are equal" << std::endl;
        return true;
    } else {
        std::cout << "they are not equal" << std::endl;
        return false;
    }
}

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

2

It can be implemented easier. The easier code usually has less errors and is easy to debug.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>bool is_palindrome(std::string text) {
return text == std::string(text.rbegin(), text.rend());
}
</code>
<code>bool is_palindrome(std::string text) { return text == std::string(text.rbegin(), text.rend()); } </code>
bool is_palindrome(std::string text) {
    return text == std::string(text.rbegin(), text.rend());
}

Even better with inclusion <algorithm> library and not creating a temporary string object

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>bool is_palindrome(std::string text) {
return std::equal(text.begin(), text.end(), text.rbegin());
}
</code>
<code>bool is_palindrome(std::string text) { return std::equal(text.begin(), text.end(), text.rbegin()); } </code>
bool is_palindrome(std::string text) {
    return std::equal(text.begin(), text.end(), text.rbegin());
}

Optimized for less CPU consumption time, but a longer code (taking into account that the first half matches the reversed second half in a palindrome):

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>bool is_palindrome(std::string text) {
return std::equal(text.begin(), text.begin() + (text.size() + 1) / 2,
text.rbegin());
}
</code>
<code>bool is_palindrome(std::string text) { return std::equal(text.begin(), text.begin() + (text.size() + 1) / 2, text.rbegin()); } </code>
bool is_palindrome(std::string text) {
    return std::equal(text.begin(), text.begin() + (text.size() + 1) / 2,
                      text.rbegin());
}

You issue in the question is int i = text.length() and access out of string bounds, undefined behavior. In particular practice you get "madam" in backwards, the unprintable first char.

5

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> #include<iostream>
#incldue<string>
bool is_palindrome(std::string text) {
int length = text.length();
for (int i = 0; i < length / 2; i++) {
if (text[i] != text[length - i - 1]) {
return false;
}
}
return true;
}
int main() {
std::string word = "madam";
if (is_palindrome(word)) {
std::cout << word << " is a palindromen";
} else {
std::cout << word << " is not a palindromen";
}
return 0;
}
</code>
<code> #include<iostream> #incldue<string> bool is_palindrome(std::string text) { int length = text.length(); for (int i = 0; i < length / 2; i++) { if (text[i] != text[length - i - 1]) { return false; } } return true; } int main() { std::string word = "madam"; if (is_palindrome(word)) { std::cout << word << " is a palindromen"; } else { std::cout << word << " is not a palindromen"; } return 0; } </code>
    #include<iostream>
    #incldue<string>
    bool is_palindrome(std::string text) {
        int length = text.length();
        for (int i = 0; i < length / 2; i++) {
            if (text[i] != text[length - i - 1]) {  
                return false;
            }
        }
        return true;
    }
    
    int main() {
        std::string word = "madam";
        if (is_palindrome(word)) {
            std::cout << word << " is a palindromen";
        } else {
            std::cout << word << " is not a palindromen";
        }
        return 0;
    }

I think you are taking string indexes wrong. The above maybe corrected and optimized solution.

1

You can use a forward and backward iterator to compare the characters front/back to middle like this too.
And better you can test correctness at compile time

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>#include <string>
#include <string_view>
constexpr bool is_palindrome(std::string_view sv)
{
auto front = sv.begin();
auto back = sv.rbegin();
for (;front < back.base(); ++front,++back)
{
if (*front != *back) return false;
}
return true;
}
int main()
{
static_assert(is_palindrome("a"));
static_assert(is_palindrome("aaa"));
static_assert(is_palindrome("tacocat"));
static_assert(!is_palindrome("ab"));
}
</code>
<code>#include <string> #include <string_view> constexpr bool is_palindrome(std::string_view sv) { auto front = sv.begin(); auto back = sv.rbegin(); for (;front < back.base(); ++front,++back) { if (*front != *back) return false; } return true; } int main() { static_assert(is_palindrome("a")); static_assert(is_palindrome("aaa")); static_assert(is_palindrome("tacocat")); static_assert(!is_palindrome("ab")); } </code>
#include <string>
#include <string_view>

constexpr bool is_palindrome(std::string_view sv)
{
    auto front = sv.begin();
    auto back = sv.rbegin();

    for (;front < back.base(); ++front,++back)
    {
        if (*front != *back) return false;
    }

    return true;
}

int main()
{
    
    static_assert(is_palindrome("a"));
    static_assert(is_palindrome("aaa"));
    static_assert(is_palindrome("tacocat"));
    static_assert(!is_palindrome("ab"));
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật