asderwsde,寻找其中的一个子字符串比如sde的个数

本文介绍了一个实用的C语言函数,用于计算一个给定字符串中特定子字符串出现的次数。通过使用strstr函数进行子字符串匹配,并遍历整个字符串来完成计数。

编写一个函数,已知一个字符串,比如asderwsde,寻找其中的一个子字符串比如sde的个数,如果没有返回0,有的话返回子字符串的个数。函数的原型为

int num_of_substring(const char* string,const char *substring);



利用strncmp

函数名: strncmp
功 能: 串比较
用 法: int strncmp(char *str1, char *str2, int maxlen);
说明:此函数功能即比较字符串str1和str2的前maxlen个字符。
如果前maxlen字节完全相等,返回值就=0;在前maxlen字节比较过程中,如果出现str1[n]与str2[n]不等,则返回(str1[n]-str2[n])。


利用strstr

包含文件:string.h
函数名: strstr
函数原型:extern char *strstr(char *str1, char *str2);
功能:查找完全匹配的子字符串。
返回值:返回该位置的指针,如找不到,返回空指针。

 

 

代码利用strstr

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

int num_of_substring(const char* string,const char *substring)
{
	int count = 0, length = strlen(substring);
	const char *p = string;

	while( (p = strstr(p, substring)) != NULL )
	{
		//puts(p);//test
		p += length;
		count++;
	}
	return count;
}
int main()
{
	char a1[] = "asderwsdejeifsderjwapfsdeejoirjwae";
	char a2[] = "sde";

	printf("%d\n", num_of_substring(a1, a2));
	return 0;
}



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值