1805: 首字母大寫
題目描述
對一個字元串中的所有單詞,如果單詞的首字母不是大寫字母,則把單詞的首字母變成大寫字母。
在字元串中,單詞之間通過空白符分隔,空白符包括:空格(’ ‘)、制表符(’\t’)、回車符(’\r’)、換行符(’\n’)。
輸入
輸入一行:待處理的字元串(長度小于100)。
輸出
可能有多組測試資料,對于每組資料,
輸出一行:轉換後的字元串。
樣例輸入
if so, you already have a google account. you can sign in on the right.
樣例輸出
If So, You Already Have A Google Account. You Can Sign In On The Right.
思路:
兩種情況:
1、字元串第一個字母前面沒有空格。如:“hello world”
這種情況下,第一步就将第一個字元(‘h’)變成大寫字母,然後根據空白符加字母的規則(即空白符的下一個字母一定是字母)來使得空白符後面的首字母變大寫。
2、字元串第一個字母前面有空格(可以不止一個)。如:" hello world"
隻需根據空白符後面一定得緊跟字母的規則來判斷
#include<stdio.h>
#include<string.h>
#include<ctype.h>
#include <stdlib.h>
int main(void)
{
char a[101];
int len, i;
while (gets(a)) {
len = strlen(a);
if (a[0] >= 'a' && a[0] <= 'z') {
a[0] = toupper(a[0]);
}
for (i = 0; i < len; i++) {
/*a[i]是空白符,a[i + 1] 是字母,必須同時滿足這兩個條件,才能将空白符後面的字母變成大寫字母*/
if (isspace(a[i]) && a[i + 1] >= 'a' && a[i + 1] <= 'z') {
a[i + 1] = toupper(a[i + 1]);
}
}
puts(a);
printf("\n");
}
return 0;
}