Convert the first character to upper case and count the number of string words in the C programming

advertisements

I am a beginner in C programming and need help! If given the following string as an example:

char prose[ ] =      "Ping! King Alfred opened the oven door
To reveal nine perfect cakes.
Oh, what a difference to history
A kitchen timer makes."

How do I write a program that contains a function Cap(&prose[0]) that will convert the first character of each word to a upper case letter?

How do I write a program that contains function int count(&prose[0]) that counts the number of words in the above prose array?


Like all things in computer science, you're given a (relatively) large problem to solve, and the solution requires you to break it into smaller problems until each is solvable... then you do that. Here, you've got two problems (assign upper case at the beginning of each word, and count words) but they're closely related, reducing your work.

Your primary problem is to identify where a word starts (and, naturally, ends); once you can do that, your problems are mostly trivial.

You can probably (within the boundary of your problem) assume that the prose string starts with a word, so you've now only got to identify where words end/resume.

If you #include <ctype.h> you have some help: isalpha(c) indicates if a character (technically an int, but realistically a character) is alphabetic. There are many other character classification functions in there but isalpha() may be all you need.

I assume you know how to iterate through your prose string, but in case you dont:

char *p = prose;
while (*p != '\0') {
    ...
    ++p;
}

that's one (of many) ways; as you go through that loop, p will point to the next character. I.e., *p will be the next character.

Now, going through the string, you can use isalpha(*p) to detect if you're looking at an alhpabetic character or not. Combined with whatever you looked at the previous time through the loop, you can decide if you're at a word break... of this isalpha() and the previous one are the same, you've either just started a new word or just ended a word. If you're just starting a word, you can increase your word count and also capitalize this word (by changing the character, such as with *p = toupper(*p); (the toupper() function is also declared in <ctype.h>)