2.已知一个字符串,比如 asderwsde,寻找其中的一个子字符串比如 sde 的个数,如果没有
返回 0,有的话返回子字符串的个数。
/* 2.已知一个字符串,比如 asderwsde,寻找其中的一个子字符串比如 sde 的个数,如果没有 返回 0,有的话返回子字符串的个数。 int strncmp(char *str1, char *str2, int maxlen); 说明:此函数功能即比较字符串str1和str2的前maxlen个字符。 如果前maxlen字节完全相等,返回值就=0; 在前maxlen字节比较过程中,如果出现str1[n]与str2[n]不等, 则返回(str1[n]-str2[n])。 */ #include<iostream> #include<stdio.h> #include<string.h> using namespace std; #define N 101 int countSubstr(char* str,char * sub) { int count=0; char *p=str; int n=strlen(sub); while(*p!='\0') { if(strncmp(p,sub,n)==0) count++; p++; } return count; } int main() { char a[]={"12345634784353456793455"}; char b[]={"345"}; printf("串1:%s \n包含 串2:%s的个数为: %d\n",a,b,countSubstr(a,b)); char c[]={"fasd45dddfghuehddfhddfggddfg"}; char d[]={"ddfg"}; printf("串1:%s \n包含 串2:%s的个数为: %d\n",c,d,countSubstr(c,d)); return 0; }