I am trying to write a function that capitalizes all words in a string using the ctype.h library. I used the isalpha(), isspace() and ispunct() functions in a conditional statement to check if the first letter of a word is an alphabet and if the character before it was whitespace or punctuation. If those conditions are met then the program converts the letter to uppercase using the toupper() function.
I ran the program and it doesn't seem to be working, it actually returned the same string input. I need someone to help me out so that I can learn and improve my C programming skills. I am learning C Programming online and I'm loving it.
#include <stdio.h>
#include <ctype.h>
/**
* *cap_string - Capitalize the first words of a string
* @s: Argument pointer to char
* Return: Pointer to s variable
*/
char *cap_string(char *s)
{
int i;
for (i = 0; s[i] != '\0'; i++)
{
if (isalpha(s[i]) && (i == 0 || (isspace(s[i - 1]) || ispunct(s[i - 1]))))
{
*s = toupper(s[i]);
}
}
return (s);
}
/**
* main - Check the code
* Return: Always 0
*/
int main(void)
{
char str[] = "Expect the best. Prepare for the worst. Capitalize on what comes.\nhello world! hello-world 012345
6hello world\thello world.hello world\n";
char *ptr;
ptr = cap_string(str);
printf("%s", ptr);
printf("%s", str);
return (0);
}
*s + iis nots[i], it'ss[0] + i.*s + iand*s + i - 1withs[i]ands[i - 1]. If i is0, thes[i - 1]will turn intos[-1], which is undefined.