电商网站开发分享,柳市做网站制作,iis网站怎么做域名绑定,做资源分享网站怎么样请阅读【嵌入式开发学习必备专栏 】 文章目录 返回从父字符串找到相同子字符串的个数 返回从父字符串找到相同子字符串的个数
在 C 语言中#xff0c;可以编写一个自定义函数来计算一个父字符串#xff08;haystack#xff09;中相同子字符串#xff08;needle#xff09…请阅读【嵌入式开发学习必备专栏 】 文章目录 返回从父字符串找到相同子字符串的个数 返回从父字符串找到相同子字符串的个数
在 C 语言中可以编写一个自定义函数来计算一个父字符串haystack中相同子字符串needle出现的次数。以下是一个简单的例子来说明如何实现这个功能
#include stdio.h
#include string.h
int count_substrings(const char *haystack, const char *needle)
{int count 0;const char *tmp haystack;// 获取子字符串的长度size_t needle_len strlen(needle);// 如果子字符串长度为0则直接返回0if (needle_len 0) {return 0;}// 循环遍历父字符串while ((tmp strstr(tmp, needle)) ! NULL) {// 找到一次子字符串计数器增加count;// 将指针移动到找到的子字符串之后以继续搜索tmp needle_len;}return count;
}int main(void)
{const char *haystack This is a test string with test words. Testing is fun, isnt it?;const char *needle test;int result count_substrings(haystack, needle);printf(The substring %s appears %d times in the string.\n, needle, result);return 0;
}在 count_substrings 函数中我们使用了 strstr 函数来搜索子字符串。每次当 strstr 返回一个非空指针时意味着找到了一个匹配的子字符串我们会增加计数器 count。然后我们将临时指针 tmp 前移子字符串的长度继续在接下来的字符串中搜索相同的子字符串。
在 main 函数中我们调用 count_substrings 函数并打印出子字符串在父字符串中出现的次数。
请注意这个函数区分大小写。如果想要一个不区分大小写的版本可以使用 strcasestr 函数如果可用或者可以将字符串转换为统一的大小写然后使用 strstr。然而strcasestr 不是标准的 ANSI C 函数因此可能在某些平台上不可用。如果需要跨平台可移植性最好自行实现一个不区分大小写的字符串搜索函数。