玄元一墨 发表于 2024-2-8 15:12:44

统计一个字符串中出现指定字符的数量

/**
* 统计一个字符串中出现指定字符的数量
* @param string str 指定的字符串
* @param char ch 指定的字符
* @return 统计数量
*/
int count_char_num(const string str, const char ch)
{
    // 统计数
    int const_num = 0;

    // 遍历字符串
    size_t pos = str.find(ch);
    while (pos != string::npos) {
      pos = str.find(ch, pos + 1);
      const_num++;
    }

    return const_num;
}
页: [1]
查看完整版本: 统计一个字符串中出现指定字符的数量