描述
输入字符串string[N](N≤100),各个单词以空格隔开,单词长度小于等于8,输入单词word[M](M≤8),在string中查找出相同的单词并统计该单词出现的次数信息,输出单词和出现次数的信息, 数据之间空一格空格。主函数输入字符串和待统计单词,编写函数count()实现统计和信息输出。
时间限制 1 内存限制 10000 类别 1
输入说明 输入一行字符以空格隔开各个单词,输入要统计的单词。
输出说明 格式输出:输出单词及其出现的次数信息,数据之间空一格。
输入样例 dog cat dog dog the abc dog hahe dog
输出样例 dog 4
代码2.0
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
char str[150]={0};
char word[10]={0};
cin.getline(str+1, 149);//将第一个字符赋值为空格
scanf("%s", word);
int lens = strlen(str+1);//要注意要从第二个开始计数,此时数组中有内容的下标是1~lens
str[lens+1] = ' ';
str[lens+2] = '\0';
str[0] = ' ';
//使第一个和最后一个单词头尾都有空格
int lenw = strlen(word);
int ans=0;
while(strstr(str, word) != NULL)
{
char *p = strstr(str, word);//strstr()函数返回值为str中第一次word出现的指针
*p = '|';//任意字符,但不能改为空格,在有相同的字符,比如eeeeee e时会出错
if (*(p-1) == ' ' && *(p+lenw) == ' ')
{
ans++;
}
}
printf("%s %d",word ,ans);
}
有用的函数:
c库函数 char *strstr(const char *haystack, const char *needle) 在字符串 haystack 中查找第一次出现字符串 needle 的位置,不包含终止符 '\0'。返回值为指针,没有就返回空指针NULL