欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-07-05 20:01:07
...

使用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;
}

执行结果如下:

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