Write a C function void title(const char str[]) that takes a zero-terminated 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. For instance, if the input is gone with the wind, the function should print: Gone With The Wind
时间: 2024-02-14 20:25:23 浏览: 86
string,CString,char*之间的转化
Certainly! Here's the updated 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') {
// Skip consecutive spaces
while (str[i] == ' ') {
i++;
}
// Move to the next line
printf(" ");
capitalize = 1;
}
}
}
```
You can use this updated `title` function to print a string such that every word is printed with its first letter capitalized. For example:
```c
int main() {
const char str[] = "gone with the wind";
title(str);
return 0;
}
```
Output:
```
Gone With The Wind
```
Please note that consecutive spaces are treated as a single separator between words.
阅读全文