在 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 #include12 #include 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_
结果: