專案開發常見字串處理模型-strstr-while/dowhile模型
---恢復內容開始---
strstr-whiledowhile模型用於在母字串中查詢符合特徵的子字串。
c語言庫提供了strstr函式,strstr函式用於判斷母字串中是否包含子字串,包含的話返回子字串的位置指標,不包含的話返回NULL。
可以用strstr函式+while模型或者 strstr函式+dowhile模型實現:
1 strstr函式+while模型:
#define _CRT_SECURE_NO_WARNINGS
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
int ncount = 0;
char *p = "abcd156445abcd456444abcd46844564abcd";
while (p = strstr(p, "abcd"))//指標p指向a
{
ncount++;
p = p + strlen("abcd");
if (*p == '\0')
{
break;
}
}
printf("字串中出現abcd的次數: %d \n", ncount); //執行可得4
system("pause");
return 0;
}
2 strstr函式+dowhile模型:
#define _CRT_SECURE_NO_WARNINGS
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
int ncount = 0;
char *p = "abcd156445abcd456444abcd46844564abcd";
do
{
p = strstr(p, "abcd");
if (p != NULL)
{
ncount++;
p = p + strlen("abcd");//找到abcd,指標繼續往前
}
else
{
break;
}
} while (*p != '\0');
printf("字串中出現abcd的次數: %d \n", ncount);
system("pause");
return 0;
}
封裝查詢子字串出現次數的API:
#define _CRT_SECURE_NO_WARNINGS
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int getCount(char*mystr, char*sub, int*ncount)
{
bool ret = false;
int tmpCount = 0;
char*p = mystr;//記得函式中不要輕易改變形參的值
//健壯程式碼
if (mystr == NULL || sub == NULL)
{
ret = false;
printf("fun getCount()err:%d (mystr == NULL || sub == NULL)\n", ret);
return ret;
}
do
{
p = strstr(p, sub);
if (p != NULL)
{
tmpCount++;
p = p + strlen(sub); //指標達到下次查詢的條件
}
else
{
break;
}
} while (*p != '\0');
*ncount = tmpCount; //間接賦值是指標存在的最大意義
ret = true;
return ret;
}
int main()
{
int count = 0;
int ret = 0;
char*p = "abcd156445abcd456444abcd46844564abcd";
char *psub = "abcd";
ret = getCount(p, psub, &count);
if (ret <= 0)
{
printf("fun getCount()err:%d", ret);
}
printf("count:%d", count);
system("pause");
return 0;
}