Merry Christmas! I'm having some trouble with a problem regarding strings. The problem statement is:
Implement a function that receives a C-styled string (s) and an array of characters (buff) together with its capacity
and concatenates into buff all the words from s which are palindromes(we consider a word to be a palindrome if read from left to right is the same as being read from right to left; i.e. "hannah" is such an example).
Avoid overflowing the array.
A word is a sequence of non-whitespace chars separated by at least one whitespace char (the first and the last word might miss the leading or trailing whitespaces).
Code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
unsigned checkWord(char word[])
{
for(int i = 0; i <= strlen(word); i++)
{
if(isspace(word[i]))
return 0;
}
return 1;
}
unsigned checkPalindrome(char str[])
{
int l = 0;
int h = strlen(str) - 1;
while (h > l)
{
if (str[l++] != str[h--])
{
return 0;
}
}
return 1;
}
void concatenatePalindromes(char s[], char buff[], int cap)
{
cap = 0;
char* word = strtok(s, " ");
while(word != NULL)
{
if(checkWord(word) == 1 && checkPalindrome(word) == 1)
{
strcat(buff, word);
}
word = strtok(NULL, " ");
}
cap = '\0';
printf("%s", buff);
}
int main()
{
char s[] = "ana john michael hannah ana stacy";
char buff[] = ""; //anahannahana
concatenatePalindromes(s, buff, 40);
return 0;
}
So I'm getting the right output(anahannahana), but I have a question about the "Avoid overflowing the array part". How do I do this? In my code I tried setting the cap to '\0' in the end, but I'm quite sure that's not it. Could you please explain?