统计字符串中子字符串的个数

使用strstr函数循环查询字符串进行统计

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

/**
 * 功能:统计母串p_str包含子串p_child_str的个数
 * 入参:p_str:母串
 *		p_child_str:需要统计的子串
 * 返回值:-1 - 入参未NULL,-2 - 子串长度为0,其他 - 统计的个数
 **/
int count_child_str(char *p_str, char *p_child_str) {
	if (NULL == p_str || NULL == p_child_str) 
		return -1;
	if (0 == strlen(p_child_str)) {
		return -2;
	}
	
	char *p_tmp = p_str;
    int cnt = 0;
	
    while((p_tmp = strstr(p_tmp, p_child_str)) != NULL){
		cnt++;
		p_tmp += strlen(p_child_str);
    }
	
    return cnt;
}

int main() {
	char *tmp = "<root><hello></hello><hello></hello></root>";
	
	printf("\n");
	printf("cnt = %d\n", count_child_str(tmp, "<hello>"));
	printf("cnt = %d\n", count_child_str(tmp, "<root>"));
	printf("cnt = %d\n", count_child_str(tmp, "<test>"));
	printf("cnt = %d\n", count_child_str(tmp, "  "));
	printf("cnt = %d\n", count_child_str(tmp, NULL));
	
	printf("\n");
	printf("cnt = %d\n", count_child_str("", "<hello>"));
	printf("cnt = %d\n", count_child_str("", "<root>"));
	printf("cnt = %d\n", count_child_str("", "<test>"));
	printf("cnt = %d\n", count_child_str("", ""));
	printf("cnt = %d\n", count_child_str("", "  "));
	printf("cnt = %d\n", count_child_str("", NULL));
	
	printf("\n");
	printf("cnt = %d\n", count_child_str(NULL, "<hello>"));
	printf("cnt = %d\n", count_child_str(NULL, "<root>"));
	printf("cnt = %d\n", count_child_str(NULL, "<test>"));
	printf("cnt = %d\n", count_child_str(NULL, "  "));
	printf("cnt = %d\n", count_child_str(NULL, NULL));
	
	return 0;
}

执行结果如下:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值