std::count最快最安全但仅适用于连续内存,需传入迭代器范围和目标字符;对C风格字符串须显式计算长度,不可直接用字面量指针;不支持Unicode且区分大小写。

直接用 std::count 最快最安全,但要注意它只适用于连续内存(比如 std::String 或数组),不能直接用于 C 风格字符串字面量而不出错。
用 std::count 统计 std::string 中字符出现次数
这是最常用也最推荐的方式,底层调用的是泛型算法,对 std::string 的 begin()/end() 迭代器做遍历。
-
std::count在头文件中,必须包含 - 第三个参数是你要统计的字符(
char类型),不是字符串或整数 - 它返回
std::iterator_traits,通常可直接赋给::difference_type int或size_t
#include #include #include int main() { std::string s = "hello world"; int cnt = std::count(s.begin(), s.end(), 'l'); std::cout << cnt << "n"; // 输出 3 }
对 C 风格字符串(const char*)使用 std::count 的陷阱
不能直接传 "hello" 的指针给 std::count,因为缺少长度信息——std::count 不会自动停在