Write code for this function: determine how many words in a given string (char*). The code should be in C.
Anonimo
I was given several minutes to write the code. When finished, I was asked to read the code line by line to him. The following is the code I wrote: int word_count(char *str) { int count = 0; bool is_prev_char_seperator = true; while (*str != '\0') { if (*str == ' ' || *str == '\r' || *str == '\n') { is_prev_char_seperator = true; } else { if (is_prev_char_seperator) { count++; } is_prev_char_seperator = false; } str++; } return count; } After that, I was asked to give several test cases for this function. Then he asked what if one may want to add new separators later. I said this can be done by saving all separator characters into a file, and then read them into an array, then compare each character in the string to each item in the char array.