Write a C function void words(const char str[ ]) that takes a zero-terminated string as an input, and shows every word of the string on a different line. A word is defined as a sequence of non-space character separated by one or more space characters.
时间: 2024-04-09 17:27:40 浏览: 56
Sure! Here's the implementation of the `words` function in C:
```c
#include <stdio.h>
void words(const char str[]) {
int i = 0;
while (str[i] != '\0') {
// Skip leading spaces
while (str[i] == ' ') {
i++;
}
// Print the word
while (str[i] != ' ' && str[i] != '\0') {
printf("%c", str[i]);
i++;
}
// Move to the next line
printf("\n");
}
}
```
You can use this function to show every word of a string on a different line. For example:
```c
int main() {
const char str[] = "Hello world! This is a test.";
words(str);
return 0;
}
```
Output:
```
Hello
world!
This
is
a
test.
```
Please note that consecutive spaces are treated as a single separator between words.
阅读全文