23.11.27 统计单词+子串出现次数

文章介绍了两道编程题目:一是统计输入字符串中的单词数量,二是找出一个大字符串中不重叠出现的小字符串的数量。涉及的知识点包括字符处理和字符串操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 一、统计单词问题

任务描述

本关任务:编写一个代码程序解决单词个数统计问题。

相关知识

做腻了数的题目,小明决定做做字符串处理的题目。这不,小明找到了这样一道题:输入一行字符,统计其中有多少个单词,单词之间用空格,逗号,或句号分隔开。

输入描述

长度不超过100000的一行字符,由空格,逗号,句号和字母组成

输出描述

包含的单词数

编程要求

根据提示,在右侧编辑器补充代码,编写一个代码程序解决单词个数统计问题。

测试用例

平台会对你编写的代码进行测试:

测试输入:Life is a journey, not a destination.; 预期输出:7

#include <stdio.h>
#include <string.h>
 
#define MAX_SIZE 100005
 
int main()
{
    char text[MAX_SIZE] = { 0 };
    int len, count = 0, is_word = 0, i;
 
    fgets(text, MAX_SIZE, stdin);
    len = (int)strlen(text);
    for (i = 0; i < len; ++i)
    {
        if (('a' <= text[i] && text[i] <= 'z') || ('A' <= text[i] && text[i] <= 'Z'))
        {
            if (!is_word)
            {
                is_word = 1;
                count++;
            }
        }
        else
            is_word = 0;
    }
 
    printf("%d\n", count);
 
    return 0;
}

二、统计不重叠子串

任务描述

本关任务:编写一个代码程序解决不重叠子串数问题。

相关知识

小明又找到一道难一点的题:给出两个字符串t和s,求出t中能找出几个不重叠的s串。比如t="tobeornottobe",s="to",则t中有2个不重叠的"to"串。

输入描述

第一行是一个正整数n,n≤10,表示接下来有几组测试数据接下来的每组数据有两个字符串t和s,都只包含字母,且长度不超过100000

输出描述

对每组数据输出对应的答案

编程要求

根据提示,在右侧编辑器补充代码,编写一个代码程序解决不重叠子串数问题。

测试用例

平台会对你编写的代码进行测试:

测试输入: 2 vvvv vvv tobeornottobe to 预期输出: 1 2

#include<stdio.h>
#include<string.h>
int main()
{
    int N;
    scanf("%d",&N);
    while(N--)
    {
        int count=0;
        char str1[100001],str2[100001];
        scanf("%s %s",str1,str2);
        int m=strlen(str1),n=strlen(str2);
        for(int j=0;j<=m-n;)
        {
            char str3[100001];
            strncpy(str3,str1+j,n);
            if(strncmp(str3,str2,n)==0)
            {
                count++;
                j+=n;
            }
            else j++;
        }
        printf("%d\n",count);
    }
    return 0;
}

只需要修改一下,就能变成统计重叠子串

#include<stdio.h>
#include<string.h>
int main()
{
        int count=0;
        char str1[100001],str2[100001];
        scanf("%s %s",str1,str2);
        int m=strlen(str1),n=strlen(str2);
        for(int j=0;j<=m-n;)
        {
            char str3[100001];
            strncpy(str3,str1+j,n);
            if(strncmp(str3,str2,n)==0)
            {
                count++;
                j++;
            }
            else j++;

    }

    printf("%d\n",count);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值