用c语言指针2.编写一个程序求一个子串在一个字符串中出现的次数,如果该字符不出现则 返回0。、
时间: 2024-03-13 15:45:59 浏览: 27
以下是一个使用 C 语言指针的程序,用于求一个子串在一个字符串中出现的次数:
```c
#include <stdio.h>
#include <string.h>
int countSubstring(char *str, char *subStr) {
int count = 0;
char *pos = str;
while ((pos = strstr(pos, subStr)) != NULL) {
++count;
pos += strlen(subStr);
}
return count;
}
int main() {
char str[] = "Hello, world! This is a test string.";
char subStr[] = "is";
int count = countSubstring(str, subStr);
printf("The substring \"%s\" appears %d times in the string.\n", subStr, count);
return 0;
}
```
在这个程序中,我们定义了一个名为 `countSubstring` 的函数,该函数接受两个参数:一个字符指针 `str` 和一个子串指针 `subStr`。该函数使用 `strstr` 函数来查找子串在原始字符串中的位置,并在找到每个子串时将计数器 `count` 增加 1。最后,该函数返回计数器的值,该值表示子串在原始字符串中出现的次数。
在 `main` 函数中,我们定义了一个测试字符串 `str` 和一个子串 `subStr`,并使用 `countSubstring` 函数来计算子串在字符串中出现的次数。最后,我们将结果输出到控制台。