分享

C和指针之字符串编程练习9(在参数1中查找匹配参数2额任意字符)

 陈喻 2021-10-19

1、问题

函数应该在第一个参数中进行查找,并返回匹配第二个参数所包含的字符的数目

2、代码实现

#include <stdio.h>
#include <string.h>


//函数应该在第一个参数中进行查找,并返回匹配第二个参数所包含的字符的数目
int count_chars(char const *str, char const *chars)
{
if (str == NULL || chars == NULL)
return 0;
int count = 0;
while ((str = strpbrk(str, chars)) != NULL)
{
//如果有匹配的记得把指针右移一下
++str;
++count;
}
return count;

}

int main()
{
const char *str = "chengongyyuhellogyy";
const char *chars = "chenyu";
printf("count_chars(%s, %s) is %d\n", str, chars, count_chars(str, chars));
return 0;
}

3、运行结果

gcc -g count_chars.c -o count_chars
./count_chars
count_chars(chengongyyuhellogyy, chenyu) is 12

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多