字符串检查总是返回假的Palidrome

String check always returns false Palidrome

本文关键字:Palidrome 返回 检查 字符串      更新时间:2023-10-16

我正在编写一个程序来检查用户的输入字符串是否是回文 我的程序总是返回 false,即使字符串是已知的回文。 我认为我的问题在于回文检查器函数,因为这总是将主函数中的答案变量设置为 false。但是,我不确定为什么总是这样。

#include "stdafx.h"
#include <iostream>
#include <String>
using namespace std;
char ReadPalIn(string Pal, int len)//converts the string into a char array
{
char PalIn[100];
if (len > 100)
{
cout << "ERROR: Palindrome possibliity too big" << endl;
system("Pause");
}
else
{
for (int i = 0; i < len; i++)
{
PalIn[i] = Pal[i];
}
}
return *PalIn;
}
bool PalindromeChecker(char Pal[],int start, int end)//checks recursively if a string is a palidrome
{
if (start == end)
{
return true; //since there is only one character
}
else if (Pal[start] != Pal[end])
{
//cout << "hi" << endl;
return false;//since that will be the case that decides when something stops being a palidrome
}
else if (start < end + 1)
{
//cout << "hi" << endl;
return PalindromeChecker(Pal, start++, end--);//since we checked both the first and last characters of the char array for palandrominess. <- word of the year?
}
else
{
return true;//base case is the string is a palindrome
}
}
int main()//test if a word is a palidrome using the functions
{
int lengthOfPal = 0;
string PalInd = "abba";
bool Answer = true;
cout << "Hello what string would you like to check?" << endl;
getline(cin, PalInd);
lengthOfPal = PalInd.length();
cout << "You input is: " << PalInd << endl;
cout << "Its Length is: " << lengthOfPal << endl;
system("Pause");
char PalIn[100] = { ReadPalIn(PalInd, lengthOfPal) };
Answer = PalindromeChecker(PalIn, 0, lengthOfPal);
if (Answer == true)
{
cout << PalInd << ": is a palidrome" << endl;
system("Pause");
}
else if(Answer == false)
{
//cout << "hi" << endl;
cout << PalInd << ": is not a palidrome" << endl;
system("Pause");
}
return 0;
}

你总是返回false因为你没有比较你认为你在比较的东西。

在最初调用PalindromeChecker()时,您使用lengthOfPal作为end参数。由于字符串的索引为零,因此初始调用应使用lengthOfPal - 1

假设您的字符串是abba.a字符位于[0][s.length() - 1](索引[3](。

您最终会遇到的另一个问题是将start++end--作为递归调用中的参数传递。这些是后递增和后递减运算符,这意味着它将startend当前值传递到递归调用中,然后调整它们的值。由于您已将函数设置为递归,因此它每次都会对startend使用相同的值。请改用前递增++start和前递减--end来避免此问题。