從鍵盤輸入一字串與一指定字元,刪除字串中所有該字元,輸出結果。
使用讀寫指標 `i`(讀取)、`j`(寫入)單次遍歷,時間複雜度 O(n),空間 O(1)。
#include <stdio.h>
#include <string.h>
#define MAX_LEN 100
int main() {
char str[MAX_LEN];
char target;
printf("請輸入字串: ");
if (fgets(str, MAX_LEN, stdin) == NULL) return 1;
str[strcspn(str, "\n")] = '\0'; // 移除換行
printf("請輸入要刪除的字元: ");
scanf(" %c", &target); // 前面空白吃掉殘留換行
// 雙指標原地刪除
size_t read = 0, write = 0;
while (str[read] != '\0') {
if (str[read] != target) {
str[write++] = str[read];
}
read++;
}
str[write] = '\0'; // 關鍵:補上結束符
printf("刪除後字串: %s\n", str);
return 0;
}
fgets() 讀取整行含空白,`strcspn` 移除尾部換行。scanf(" %c", &target):格式字串前的**空白**會自動跳過任何空白字元(含前一行殘留的 `\n`),避免讀到換行符。請輸入字串: hello world
請輸入要刪除的字元: l
刪除後字串: heo word
| 錯誤寫法 | 問題 | 正確做法 |
|---|---|---|
scanf("%s", str) | 遇到空白停止,無法讀含空白字串 | fgets(str, MAX_LEN, stdin) |
scanf("%c", &ch) 直接讀 | 讀到上一行殘留 `\n` | scanf(" %c", &ch) 或 getchar() 吃掉 `\n` |
| 刪除後忘記 `str[write] = '\0'` | 字串未正確結束,輸出亂碼 | 務必在迴圈結束後補 `\0` |
| 用 `strlen(str)` 在迴圈條件中 | 每次迴圈呼叫 strlen,O(n²);且刪除後長度變化 | 用 `while (str[read])` 單次遍歷 |
若需刪除一組字元(如所有母音),可建立查找表:
bool delete_set[256] = {false};
delete_set['a'] = delete_set['e'] = delete_set['i'] = delete_set['o'] = delete_set['u'] = true;
// 迴圈中判斷: if (!delete_set[(unsigned char)str[read]]) ...