用C语言编写函数将一个字符串中每一个单词的第一个字母转换为大写。
时间: 2024-03-15 14:45:38 浏览: 18
可以使用以下函数实现:
```c
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void capitalize(char *str) {
int i;
int len = strlen(str);
int is_new_word = 1; // 判断是否为新的单词
for (i = 0; i < len; i++) {
if (is_new_word && isalpha(str[i])) {
str[i] = toupper(str[i]); // 转换为大写
is_new_word = 0;
} else if (isspace(str[i])) {
is_new_word = 1;
}
}
}
int main() {
char str[] = "hello world, this is a test";
capitalize(str);
printf("%s\n", str); // 输出 "Hello World, This Is A Test"
return 0;
}
```
该函数遍历字符串中的每个字符,如果是新单词的第一个字母,则将其转换为大写。使用 `isspace` 函数判断是否为单词的分隔符。