首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C 語言統計字符出現次數:封裝函數與查找函數複用

     編輯:程式設計綜合問答

原始示例

char word[] = "banana";
int count = 0;
for (int i = 0; word[i] != '\0'; i++)
    if (word[i] == 'a') count++;
printf("%d", count); // 輸出 3

練習 6:封裝為 count 函數

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

練習 7:複用 find 函數(假設已有)

// 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 語言核心功底,熟練掌握指針遍歷、空值終止、函數複用至關重要。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved