己有一个字符串 s,目标子串d,统计d在s中出现的该数。部分代码己提供,请在此基础上补充完成程序。 int getstrnum(char *s.,char *d) { int num=0; char *t: t=d; for(;*s;s++) { //请补充完成程序 } return num; } int _tmain (int argc, _TCHAR* argv []) { char *s=“Guizhou University is the only key university in Guizhou prioritized to develop itself in line with the criteria of the 211 Project”; cher *d=“th”; printf"%d\n", setstrnum (s. d)) ; return 0; }
时间: 2024-03-07 16:48:19 浏览: 74
统计输入的某个字符的个数
4星 · 用户满意度95%
完成的代码如下:
```
#include <stdio.h>
#include <string.h>
int getstrnum(char *s, char *d) {
int num = 0;
char *t = d;
int len = strlen(d);
for (; *s; s++) {
if (*s == *t) {
t++;
if (*t == '\0') {
num++;
t = d;
}
} else {
t = d;
}
}
return num;
}
int main() {
char *s = "Guizhou University is the only key university in Guizhou prioritized to develop itself in line with the criteria of the 211 Project";
char *d = "th";
printf("%d\n", getstrnum(s, d));
return 0;
}
```
解释:首先,我们需要定义两个指针s和t,分别指向字符串s和目标子串d的首字符,然后遍历字符串s,逐个字符进行比较。如果字符相同,指针t向后移动一位,如果指针t指向目标子串的结尾,则说明目标子串出现了一次,计数器num加1,同时指针t重新指向目标子串的首字符。如果字符不同,指针t重新指向目标子串的首字符。最后返回计数器num即可。
阅读全文