一、统计单词问题
任务描述
本关任务:编写一个代码程序解决单词个数统计问题。
相关知识
做腻了数的题目,小明决定做做字符串处理的题目。这不,小明找到了这样一道题:输入一行字符,统计其中有多少个单词,单词之间用空格,逗号,或句号分隔开。
输入描述
长度不超过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;
}