統計字串出現的次數(C)
阿新 • • 發佈:2020-12-13
//標頭檔案 #include <stdio.h> #include <stdlib.h> #include <string.h> //主函式 int main() { //定義字串1 char *src = "hello llo llo llo world"; //定義字串2 char *dist = "llo"; //宣告統計次數的變數 int count = 0; //strstr函式判斷字串2是否是字串1的子串如果是返回第一次出現的位置到結尾的字串 不是返回NULL //返回的字串為一個指標 char *ret = strstr(src, dist); //使用while判斷返回值是否為NULL while (ret != NULL) { count += 1; //每判斷一次截斷一個字串2 //strlen函式返回字串的長度不包含‘\0’ ret += strlen(dist); //再次呼叫strstr函式判斷 ret = strstr(ret, dist); } //打印出現的次數 printf("%d", count); //程式暫停 system("pause"); //程式正常退出 return 0; }