Write a C function void title(const char str[]) that takes a zeroterminated string as an input, and prints it such that every word of the string is printed with its first letter capitalized (upper-case). Here, a word is defined as a sequence of non-space character separated by one or more space characters.
时间: 2024-04-09 09:27:47 浏览: 53
用函数输出文字.c
Certainly! Here's the implementation of the `title` function in C:
```c
#include <stdio.h>
#include <ctype.h>
void title(const char str[]) {
int i = 0;
int capitalize = 1;
while (str[i] != '\0') {
// Skip leading spaces
while (str[i] == ' ') {
i++;
}
// Capitalize the first letter of the word
if (capitalize) {
printf("%c", toupper(str[i]));
capitalize = 0;
} else {
printf("%c", str[i]);
}
// Move to the next character
i++;
// Check if the current word has ended
if (str[i] == ' ' || str[i] == '\0') {
// Move to the next line
printf("\n");
capitalize = 1;
}
}
}
```
You can use this function to print a string such that every word is printed with its first letter capitalized. For example:
```c
int main() {
const char str[] = "hello world! this is a test.";
title(str);
return 0;
}
```
Output:
```
Hello
World!
This
Is
A
Test.
```
Please note that consecutive spaces are treated as a single separator between words.
阅读全文