本文整理了一組經典的 C 語言字符串操作習題,涵蓋遍歷、逆序、查找、統計、庫函數對應、自定義 strindex、strcmp、不區分大小寫比較、判斷互為逆序等核心知識點,並提供標準實現與詳細註釋,適合初學者鞏固指針與數組操作。
void traversal(char s[]) {
for (int i = 0; s[i] != '\0'; i++)
printf("%c\n", s[i]);
}
void reverse_print(char s[]) {
int len = strlen(s);
for (int i = len - 1; i >= 0; i--)
printf("%c\n", s[i]);
}
int find(char word[], char letter) {
for (int i = 0; word[i] != '\0'; i++)
if (word[i] == letter) return i;
return -1;
}
int find(char word[], char letter, int start) {
for (int i = start; word[i] != '\0'; i++)
if (word[i] == letter) return i;
return -1;
}
int count(char s[], char letter) {
int cnt = 0;
for (int i = 0; s[i] != '\0'; i++)
if (s[i] == letter) cnt++;
return cnt;
}
int count(char s[], char letter) {
int cnt = 0, pos = 0;
while ((pos = find(s, letter, pos)) != -1) {
cnt++;
pos++; // 從下一位繼續找
}
return cnt;
}
| 功能 | ANSI C 庫函數 |
|---|---|
| 字符串轉大寫 | 無標準函數,常用 toupper 逐字符轉換 |
| 查找字符位置 | strchr |
| 查找子串位置 | strstr |
strindexint strindex(char s[], char t[]) {
int i, j, k;
for (i = 0; s[i] != '\0'; i++) {
for (j = i, k = 0; t[k] != '\0' && s[j] == t[k]; j++, k++);
if (t[k] == '\0' && k > 0) return i;
}
return -1;
}
邏輯:外層遍歷主串起始位,內層同時推進主串與子串比較,若子串走到末尾(t[k]=='\0')且匹配長度>0,返回起始下標。
strcmp(字典序)int strcmp(char s[], char t[]) {
int i;
for (i = 0; s[i] == t[i]; i++)
if (s[i] == '\0') return 0;
return s[i] - t[i];
}
strcmp_ignore_caseint strcmp_ignore_case(char s[], char t[]) {
int i;
for (i = 0; toupper(s[i]) == toupper(t[i]); i++)
if (s[i] == '\0') return 0;
return toupper(s[i]) - toupper(t[i]);
}
int is_reverse(char s[], char t[]) {
int len = strlen(s);
if (len != strlen(t)) return 0;
for (int i = 0, j = len - 1; i < len; i++, j--)
if (s[i] != t[j]) return 0;
return 1;
}
原代碼錯誤:j=strlen(t) 越界,應為 len-1;循環條件 j>0 應為 i<len。
\0 結束標誌與下標邊界。strchr、strstr、strcmp),理解底層實現。這組習題涵蓋了 C 語言字符串處理的核心技巧,反覆練習能顯著提升指針與數組操作能力。