统计单词数

统计单词数

链接:http://ybt.ssoier.cn:8088/problem_show.php?pid=1400

【题目描述】

一般的文本编辑器都有查找单词的功能,该功能可以快速定位特定单词在文章中的位置,有的还能统计出特定单词在文章中出现的次数。

现在,请你编程实现这一功能,具体要求是:给定一个单词,请你输出它在给定的文章中出现的次数和第一次出现的位置。注意:匹配单词时,不区分大小写,但要求完全匹配,即给定单词必须与文章中的某一独立单词在不区分大小写的情况下完全相同(参见样例1),如果给定单词仅是文章中某一单词的一部分则不算匹配(参见样例2)。

【输入】

第 1 行为一个字符串,其中只含字母,表示给定单词;

第 2 行为一个字符串,其中只可能包含字母和空格,表示给定的文章。

 

【输出】

只有一行,如果在文章中找到给定单词则输出两个整数,两个整数之间用一个空格隔开,分别是单词在文章中出现的次数和第一次出现的位置(即在文章中第一次出现时,单词首字母在文章中的位置,位置从0开始);如果单词在文章中没有出现,则直接输出一个整数-1。

【输入样例】

To
to be or not to be is a question

【输出样例】

2 0

【提示】

样例输入:

样例 #2:

to

Did the Ottoman Empire lose its power at that time

样例输出:

样例 #2:

-1

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
using namespace std;
int ans=0,pos=-1;
char s1[15],s2[1000005],s3[1000005];
int main()
{
  gets(s1);
  gets(s2);
  int len1=strlen(s1),len2=strlen(s2);
  s3[0]=' ';s3[1]='';
  strcat(s3,s2);
  s2[0]=' ';s2[1]='';
  strcat(s3,s2);
  for (int i=len2-len1+1;i>=1;i--)//从后往前遍历
  {
     strncpy(s2,s3+i,len1);s2[len1]='';
     if (s3[i-1]==' '&&s3[i+len1]==' '&&strcmp(strlwr(s1),strlwr(s2))==0) {ans++;pos=i-1;}
  }
  if (pos!=-1) printf("%d ",ans);
  printf("%d
",pos);
  printf("
");
  return 0;   
}
#include<iostream>
#include<string>
using namespace std;

string s1,s2;
int ans=0,pos=-1;
int main()
{
  getline(cin,s1);
  getline(cin,s2);
  s1.insert(0," "); s1.insert(s1.size()," ");
  s2.insert(0," "); s2.insert(s2.size()," ");
  for (int i=0;i<s1.size();i++)
    if (s1[i]>='A'&&s1[i]<='Z') s1[i]+=32;
  for (int i=0;i<s2.size();i++)
    if (s2[i]>='A'&&s2[i]<='Z') s2[i]+=32; 
    
  while ((pos=s2.find(s1,pos+1))!=string::npos)//查找有匹配
      ans++;
  if (ans)
    cout<<ans<<" "<<s2.find(s1,0)<<endl;
  else
    cout<<-1<<endl; 
  return 0;
}
原文地址:https://www.cnblogs.com/EdSheeran/p/7306984.html