请编写一个查找子字符串的程序,并统计子字符串出现的次数。
**输入格式要求:"%s" 提示信息:"请输入主串:" "请输入要查找的串:"
**输出格式要求:"%s,%s:" "子串出现的次数:%d\n" "子串不在主串中\n"
程序运行示例1如下:
请输入主串:Hello,world!
请输入要查找的串:l
Hello,world!,l:子串出现的次数:3
程序运行示例2如下:
请输入主串:Hello,world!
请输入要查找的串:abc
Hello,world!,abc:子串不在主串中
1 #include<stdio.h> 2 #include<string.h> 3 #define N 80 4 main() 5 { 6 char str1[N], str2[N]; 7 int count = 0, i, j, temp, k = 0; 8 printf("请输入主串:"); 9 scanf("%s", str1); 10 printf("请输入要查找的串:"); 11 scanf("%s", str2); 12 for (i = 0; i < strlen(str1) ; i++) 13 { 14 if (str1[i]==str2[0]) 15 { 16 temp = i; 17 for (j = 0; j < strlen(str2); i++, j++) 18 { 19 if (str1[i]!=str2[j]) 20 break; 21 else 22 k += 1; 23 } 24 if (k == strlen(str2)) 25 count += 1; 26 k = 0; 27 i = temp; 28 } 29 } 30 printf("%s,%s:", str1, str2); 31 if (count == 0) 32 printf("子串不在主串中\n"); 33 else 34 printf("子串出现的次数:%d\n", count); 35 }
原文:https://www.cnblogs.com/20201212ycy/p/14807255.html