C语言统计字符串A在字符串B出现的次数
时间: 2024-11-16 17:13:57 浏览: 22
c代码-计算 ab ba的个数
在C语言中,你可以使用循环结构和字符串处理函数来统计字符串A在字符串B中出现的次数。这里是一个简单的示例代码:
```c
#include <stdio.h>
#include <string.h>
int count_occurrences(const char* strB, const char* substrA) {
int count = 0;
size_t lenB = strlen(strB);
size_t lenA = strlen(substrA);
for (size_t i = 0; i <= lenB - lenA; ++i) {
if (strncmp(strB + i, substrA, lenA) == 0) { // 使用strncmp避免缓冲区溢出
count++;
}
}
return count;
}
int main() {
const char* stringB = "Hello, how are you? I'm doing great!";
const char* stringA = "are";
int occurrences = count_occurrences(stringB, stringA);
printf("String '%s' appears %d times in string '%s'.\n", stringA, occurrences, stringB);
return 0;
}
```
这个`count_occurrences`函数会遍历字符串B,并通过`strncmp`函数比较子串是否匹配,如果匹配则计数加一。最后返回计数值。
阅读全文