统计单词在第一次出现的位置和字符串中出现的次数
微软办公软件word想推出新的功能,即对于指定的单词,可以统计在整个字符串中出现的次数,并输出该单词在字符数组中第一次出现是第几个单词(不区分大小写,也就是说“HeLLo”和“hello”算同一个单词),如果该单词没有出现在该字符串中,则输出-1。单词之间用单个空格隔开。
输入描述 :
输入为2行:第一行为一个字符串,长度不超过500。第二行为需要统计的单词,长度不超过100。
输出描述 :
输出为一行,如果该单词没有出现在字符串中,则输出-1,如果该单词出现在字符串中,输入该单词第一次出现是第几个单词以及该单词在整个字符串中出现的次数,中间用单个空格隔开。
样例输入 :
ab AbC def aBc abc def abC
ABc
样例输出 :
2 4
用C++写,最好用函数,不用循环和数组,谢谢!
你的这个不用循环和数组那是不可能的
首先,字串本身就是数组,而你要在一组数据中找一个匹配的数组,肯定要用循环
以下是参考程序
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int fun(const string& src, string des,int &pos)
{
string str = src;
string substring;
string::size_type start = 0, index;
int count=0,ct=0;
pos=ct=0;
transform(des.begin(), des.end(), des.begin(), ::toupper);
do
{
index = str.find_first_of(" ",start);
if (index != string::npos)
{
substring = str.substr(start,index-start);
transform(substring.begin(), substring.end(), substring.begin(), ::toupper);
ct++;
if (substring==des)
{
count++;
if (pos==0)
pos=ct;
}
start = str.find_first_not_of(" ",index);
if (start == string::npos) return count;
}
}
while(index != string::npos);
substring = str.substr(start);
transform(substring.begin(), substring.end(), substring.begin(), ::toupper);
ct++;
if (substring==des)
{
count++;
if (pos==0)
pos=ct;
}
return count;
}
int main()
{
string str;
getline(cin,str);
string str1;
cin >> str1;
int pos,ct;
ct= fun(str,str1,pos);
cout << pos << " " << ct << endl;
return 0;
}
测试结果
下一篇:数据中心有什么安全隐患?具体列举
上一篇:mvc模式中的控制器