輸入一行文字,將其中每個單字的首字母由小寫改為大寫。單字間以一個以上空白分隔。
#include <stdio.h>
#include <ctype.h> // 提供 toupper(), isspace()
#include <string.h>
#define MAX_LEN 1000
int main() {
char str[MAX_LEN];
printf("請輸入一行文字: ");
if (fgets(str, MAX_LEN, stdin) == NULL) {
return 1;
}
// 移除 fgets 保留的換行符
str[strcspn(str, "\n")] = '\0';
// 處理第一個字元
if (str[0] != '\0' && islower((unsigned char)str[0])) {
str[0] = toupper((unsigned char)str[0]);
}
// 遍歷偵測「空白後的首字母」
for (size_t i = 1; str[i] != '\0'; i++) {
if (isspace((unsigned char)str[i-1]) && !isspace((unsigned char)str[i]) && islower((unsigned char)str[i])) {
str[i] = toupper((unsigned char)str[i]);
}
}
printf("轉換結果: %s\n", str);
return 0;
}
ctype.h 函式:`islower()`、`toupper()`、`isspace()` 處理字元分類與轉換,**參數需轉為 `unsigned char` 避免未定義行為**。fgets():安全讀取整行,含空白,自動防止緩衝區溢位。strcspn(str, "\n"):快速定位換行符位置並移除。請輸入一行文字: hello world c programming
轉換結果: Hello World C Programming
多重空白保持不變,每個單字首字母正確大寫。