I am building a program that checks if a given String is a palindrome and whenever I try to reverse the char array, "palindromeCheckBuffer" returns "ü" instead of the reversed array when I print it.
String userInput = "test" //Placeholder value
int userInputCharLength = userInput.length() + 1;
char palindromeCheck[userInputCharLength];
userInput.toCharArray(palindromeCheck, userInputCharLength);
char palindromeCheckBuffer[userInputCharLength];
for (int i = userInputCharLength,x=0; i != 0; i--, x++){
palindromeCheckBuffer[x] = palindromeCheck[i];
}
I thought I understood what that snippet was doing wrong; now I'm totally confused.
On a third look, I think I had it right the first time.
Pop quiz time:
What's the index of the last array element? What's the value of userInputCharLength the first time through the loop? Is that value less than or equal to the index of the last array element?
uiserInputCharLength is giving you a problem.
With "test", that will be 5, which is correct for the size of the char array, but that will not work in the for loop:
palindromeCheckBuffer[0] = palindromeCheck[5]; << this is past end of array
palindromeCheckBuffer[1] = palindromeCheck[4]; << this is terminating NULL
palindromeCheckBuffer[2] = palindromeCheck[3];
palindromeCheckBuffer[3] = palindromeCheck[2];
palindromeCheckBuffer[4] = palindromeCheck[1];
also, you never copy the first character
< looks like @van_der_decken added a bit to their post while I was typing >
for (int i = 0; i <= userInputCharLength / 2; i++)
{
if (palindromeCheck[i] != palindromeCheck[userInputCharLength - i])
return(false); // not a palindrome
}
return(true); // must be a palindrome
Let's pretend that in one buffer there can be two sets of chars that can be pointed to by two different char pointers and each sub-string is delimited at both ends.
To compare the two we need a pointer to each and a delimiter at the end of each whether a NUL, space, or punctuation.
How is that fundamentally different between two strings except that strings are always delimited by NUL?
I don't usually use string.h functions because I Write My Own and have for decades.
if you don't count spaces, you can apply this to sentences. a famous one (kinda in the news right now) : "A MAN A PLAN A CANAL PANAMA"
the function would then become something like (also ignoring case)
bool isPalindrome(const char* str) {
size_t start = 0, end = strlen(str) - 1;
while (start < end) {
if (isspace(str[start])) start++;
else if (isspace(str[end])) end--;
else if (tolower(str[start++]) != tolower(str[end--])) return false;
}
return true;
}
void setup() {
Serial.begin(115200);
const char* testStrings[] = {"RADAR", "LEVEL", "CIVIC", "ROTATOR", "MADAM", "KAYAK", "NOON", "NOT GOOD", "A MAN A PLAN A CANAL PANAMA"};
for (const char * s : testStrings) {
Serial.print(s);
if (isPalindrome(s))
Serial.println(" is a palindrome!");
else
Serial.println(" is not a palindrome.");
}
}
void loop() {}