传智播客视频学习 ---->>>> 项目开发模型_strstr_while模型(在 str 中查找子串 str2 的出现次数)

 

在 str 中查找子串 str2 的出现次数

 

 // 参数:1->源字符串,2->查找的字符串,3->计数
 int getStringCount(char *strSource, char *strFind, int *nCount)

第三个参数是查找的数量,可以返回查找多个str的数量,查找两个字符串的数量
函数返回的是错误码

 

代码:

 1 // 
 2 // atuo @silent
 3 // date 2015/11/23
 4 //
 5 
 6 // 在一个字符串中查找另一个字符串出现的次数
 7 
 8 #ifndef _CODE_STRING_STRSTR_WHILE_H_
 9 #define _CODE_STRING_STRSTR_WHILE_H_
10 
11 #include <stdio.h>
12 #include <string.h>
13 
14 // 参数:1->源字符串,2->查找的字符串,3->计数
15 int getStringCount(char *strSource, char *strFind, int *nCount){
16     
17     int        errorCode = 0;            // 定义错误码
18     int        nTempCount = 0;    // 定义临时的计数器
19     char    *str = strSource;        // 定义临时的源字符串
20     char    *buf = strFind;            // 定义临时的查找字符串
21 
22     if (strSource == NULL || strFind == NULL || nCount == NULL){
23 
24         errorCode = -1;                // 设置错误码
25         // 打印错误信息,日志
26         printf("func getStringCount() error = %d, line = %d \n", errorCode, 21);
27         return errorCode;            // 返回错误码
28     }
29 
30     while (str = strstr(str, buf)){
31         nTempCount++;
32         str = str + strlen(buf);    // 让指针达到查找条件
33         if (str == '\0'){
34             break;
35         }
36     }
37 
38     // 获得计数,因为是跟主函数中的count公用一个内存地址,借此将计数传递给主函数中的count变量
39     *nCount = nTempCount;            // *号的作用,在左边是设置指定地址的内存空间的内容
40 
41     return errorCode;
42 }
43 
44 int main(){
45     
46     char *strSource = "abcd1123abcd 123abcd abcdotin";    // 源字符串
47     char *strFind = "abcd";        // 要查找的字符串
48 
49     int count = 0;                // 次数
50 
51     // 因为参数都是指针,所以最后一个参数用取地址
52     int errorCode = getStringCount(strSource, strFind, &count);
53     //int errorCode = getStringCount(NULL, NULL, NULL);
54 
55     // 检查是否出现错误
56     if (0 != errorCode ){
57         printf("func getStrCount() error = %d, \n", errorCode);
58         return errorCode;
59     }
60 
61     printf("count = %d \n", count);    // 输出查找到的次数
62     
63     system("pause");
64     return 0;
65 }
66 
67 #endif // _CODE_STRING_STRSTR_WHILE_H_

 

结果:

 

posted @ 2015-11-23 01:03  silent-bobo  阅读(192)  评论(0编辑  收藏  举报