Count and Rewrite Strings Without a Library
MediumThe string library arrives next lesson. Before it does, write the two loops it is built out of, so that nothing about it can look like magic later. main is written for you and needs no changes. It declares three arrays, char word[] = "memory", char phrase[] = "banana bread" and char tag[] = "cs", each of them a writable copy of its literal with the terminator already in place, and each of them printed twice: once as a character count beside its sizeof, and once after a character has been replaced in it. There is no input to read, so every run produces the same six lines. Your job is the two functions. int count_characters(const char *text) returns how many characters come before the null terminator, which means starting a counter at 0 and walking forward while text[count] is not '\0', stopping the moment it is. The terminator is the end marker rather than a character of the string, so it is never counted, which is why the printed count is always one less than the sizeof printed beside it: sizeof measures the whole array in bytes and the terminator is one of them. Look at the tag line to see that in miniature, since "cs" is two characters in an array of three. void replace_character(char *text, char target, char replacement) walks the same way and assigns replacement to every position holding target, leaving everything else alone. Two things about its signature are deliberate. There is no count parameter on either function, because unlike every other array in chapter 4 a string carries its own end marker and needs no length beside it; the terminator is the bound. And text is const char * in the first function and plain char * in the second, because the first only reads while the second writes, and the write is legal only because main declared arrays rather than pointers to literals. Had main written char *word = "memory", the same assignment would be modifying a string literal, which is undefined behaviour. Do not use any function from string.h, which the next lesson introduces properly, and note that phrase contains three a characters plus a fourth inside bread, so a loop that stops at the first match or at the space will not produce the expected line. main returns 0 on its only path, since the checker treats a nonzero exit status as a failure however correct the output looks.
Success Criteria
Your code must pass 1 test case(s) to complete this exercise. 3 hint(s) are available if you need help.
Sign in to track your progress
You can work on exercises as a guest, but sign in to track your progress and save your submissions.