C语言统计字符串中某指定字符串出现的次数

这里为封装函数
int sumStr(char*s1, char* s2)//统字符串s2在字符串s1中出现的次数
{
    int i = 0;
    char* p = s1;
    while ((p = strstr(p, s2)) != NULL)
    {
        i++;
        p += strlen(s2);
    }
    return i;
}

在C语言中,统计字符串中某个单词出现次数需要经过以下几个步骤: 1. **读取字符串**:首先,你需要从用户那里获取输入的字符串2. **分割字符串**:将字符串按照空格或其他特定分隔符(如逗号、句点等)拆分成单词数组。可以使用`strtok()`函数或者自定义循环实现这个过程。 3. **创建计数数组**:初始化一个大小为指定单词长度的最大计数数组,用于存储每个单词出现的次数。 4. **遍历单词**:遍历单词数组,对于每个单词,检查它是否存在于计数数组内。如果存在,计数加一;如果不存在,将其添加到计数数组并设置为1。 5. **累加计数**:最后,遍历计数数组,统计总出现次数。 6. **输出结果**:将结果输出给用户。 下面是一个简单的示例代码片段,展示如何实现这一功能,注意这只是一个基本的示例,并未处理特殊情况: ```c #include <stdio.h> #include <string.h> #define MAX_WORDS 100 #define MAX_WORD_LEN 50 int count_words(char *str, char *word) { int word_count[MAX_WORDS] = {0}; char *token; token = strtok(str, " "); // 使用空格作为分隔符 while (token != NULL) { if (strlen(token) <= MAX_WORD_LEN && strcmp(token, word) == 0) { word_count[tokoword_index(token)]++; // 将单词转换为数组索引 } token = strtok(NULL, " "); } return word_count[tokoword_index(word)]; } void main() { char str[1000], word[MAX_WORD_LEN]; printf("请输入字符串:"); fgets(str, sizeof(str), stdin); str[strlen(str) - 1] = '\0'; // 去除行尾的换行符 printf("请输入要搜索的单词:"); scanf("%s", word); int occurrences = count_words(str, word); printf("单词 \"%s\" 出现了 %d 次。\n", word, occurrences); } ``` 在这个例子中,`tokoword_index()`函数用于将单词转换为在`word_count`数组中的索引,实际项目中可能需要根据实际情况定制。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值