0
点赞
收藏
分享

微信扫一扫

HarmonyOS 应用开发之@Extend装饰器:定义扩展组件样式

曾宝月 04-03 10:00 阅读 1


请阅读【嵌入式开发学习必备专栏 】


文章目录

返回从父字符串找到相同子字符串的个数

在 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,则直接返回0
    if (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, isn't 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 函数,因此可能在某些平台上不可用。如果需要跨平台可移植性,最好自行实现一个不区分大小写的字符串搜索函数。

举报

相关推荐

0 条评论