char word[] = "banana";
int count = 0;
for (int i = 0; word[i] != '\0'; i++)
if (word[i] == 'a') count++;
printf("%d", count); // 輸出 3
int count_char(const char* str, char target) {
int cnt = 0;
for (int i = 0; str[i] != '\0'; i++)
if (str[i] == target) cnt++;
return cnt;
}
// 調用
int n = count_char("banana", 'a'); // 3
// find(str, start, target) 返回 target 在 str 中從 start 開始首次出現的索引,未找到返回 -1
int count_char_find(const char* str, char target) {
int cnt = 0, pos = 0;
while ((pos = find(str, pos, target)) != -1) {
cnt++;
pos++; // 繼續查找下一位置
}
return cnt;
}
'\0' 結尾,遍歷條件 str[i] != '\0'。const char* 參數防止誤修改原字符串。find 避免重複造輪子,體現模塊化思想。此類基礎字符串操作是 C 語言核心功底,熟練掌握指針遍歷、空值終止、函數複用至關重要。