62. (待补)统计一个字符在字符串中出现次数 与 统计一个字符串在另一字符串中出现次数。

 

使用strchr

 

自实现

 

 

 

使用strstr

 

自实现

 1 #include <stdio.h>
 2 
 3 int getSubstrCount(char* str,char* subStr)
 4 {
 5     int count = 0;
 6     while(*str && *subStr)//遍历大串,另,传入的小串如果为空,直接不作判断。
 7     {
 8         int i;
 9         //在大串中碰见与小串首字母相同的字母时,则进去for循环开始进行后续连续判断,如果有不同,则终止循环。如果完全相同,则小串会遍历到\0正常结束循环。
10         for(i = 0;*(str+i) == *(subStr+i)&& *(subStr+i) != '\0';i++);
11 
12         //如果for循环结束时,小串已经遍历到\0,则表示与小串相同。并更新遍历大串的新起点位置。
13         if(*(subStr+i) == '\0')
14         {
15             count++;
16             str = str+i;
17         }
18         else//如果for循环结束时,小串未遍历到\0.则表示与小串不同,并更新遍历大串的新起点位置。
19             str++;
20     }
21     return count;
22 }
23 
24 int main()
25 {
26     char* str = "a   aaaaaaaaaab";
27     char* subStr = "   ";
28     printf("count = %d\n",getSubstrCount(str,subStr));
29     return 0;
30 }

 

posted @ 2018-08-29 18:18  2018年8月10日注册  阅读(227)  评论(0编辑  收藏  举报