題目要求
- 從鍵盤輸入字符串,包含大寫字母、小寫字母及其他字符。
- 編寫程序將三類字符按順序分離,分別存入三個字符數組,原數組不變。
- 用三個子函數分別實現大寫、小寫、其他字符的分離。
- 子函數形式參數為指向字符的指針變量。
- 主函數調用三個子函數並顯示原字符串及三類分離結果。
參考實現
#include <stdio.h>
#include <string.h>
void extractUpper(const char *src, char *dest) {
int i = 0;
while (*src) {
if (*src >= 'A' && *src <= 'Z') dest[i++] = *src;
src++;
}
dest[i] = '\0';
}
void extractLower(const char *src, char *dest) {
int i = 0;
while (*src) {
if (*src >= 'a' && *src <= 'z') dest[i++] = *src;
src++;
}
dest[i] = '\0';
}
void extractOther(const char *src, char *dest) {
int i = 0;
while (*src) {
if (!(*src >= 'A' && *src <= 'Z') && !(*src >= 'a' && *src <= 'z'))
dest[i++] = *src;
src++;
}
dest[i] = '\0';
}
int main() {
char str[100], upper[100], lower[100], other[100];
printf("請輸入字符串: ");
fgets(str, sizeof(str), stdin);
str[strcspn(str, "\n")] = '\0'; // 去除換行符
extractUpper(str, upper);
extractLower(str, lower);
extractOther(str, other);
printf("原字符串: %s\n", str);
printf("大寫字母: %s\n", upper);
printf("小寫字母: %s\n", lower);
printf("其他字符: %s\n", other);
return 0;
}
關鍵點解析
- 指針遍歷: 子函數接收
const char *src,通過 while(*src) 逐字符判斷,符合條件寫入目標數組。
- 目標數組結尾: 每個函數最後必須添加
'\0' 結束符,否則 printf("%s") 會讀越界。
- 原數組不變: 只讀遍歷
src,不修改原字符串內容。
- 輸入處理: 使用
fgets 讀取整行,含空格;去除尾部換行符。
擴展思路
- 若要求動態分配目標數組,可先統計各類字符數量,再
malloc 精確大小。
- 若允許
ctype.h,可用 isupper()、islower() 替代手動範圍判斷,提高可讀性與移植性。