count在c语言中怎么用

来源:这里教程网 时间:2026-02-21 16:51:02 作者:

count 在 C 语言中的用法

count 在 C 语言中主要用于计算一个字符或子字符串在给定字符串中出现的次数。它是一个库函数,通常位于 头文件中。

原型

<code>size_t count(const char *s, int c);</code>

参数

立即学习“C语言免费学习笔记(深入)”;

s
:要搜索的字符串。
c
:要查找的字符。

返回值

返回字符

c
在字符串
s
中出现的次数。如果字符
c
未在字符串
s
中找到,则返回 0。

用法

count 函数的使用非常简单,只需将要搜索的字符串和要查找的字符作为参数传递即可。例如,以下代码计算字符串 "Hello, world!" 中字母 'o' 出现的次数:

<code>#include <stdio.h>
#include <string.h>
int main()
{
    char str[] = "Hello, world!";
    int count_o = count(str, 'o');
    printf("The character 'o' appears %d times in the string.\n", count_o);
    return 0;
}</code>

输出

<code>The character 'o' appears 2 times in the string.</code>

相关推荐