您的位置:首页 > 其它

统计单词数

2012-04-03 16:20 183 查看
#include <iostream>
#include <sstream>
#include <stdio.h>
#include <string>
#include <cstring>
#include <cctype>
using namespace std;
/* 耗时什么的,完全不在乎了,已经被搞吐了 */
void stolower(string& str)
{
for(int i = 0; i < str.size(); i++)
if(isalpha(str[i]))
str[i] = tolower(str[i]);
}
int pos[1000000 + 10];
int main()
{
string key, word;
string article;
char c_key[30];
while(cin.peek() == ' ')
cin.ignore();
cin.getline(c_key, 30);
if (cin.peek() == '\n')
cin.ignore();
for(int i = 0; i < 15; i++)
{
if(!isalpha(c_key[i]))
{
c_key[i] = 0;
break;
}
}
key = c_key;
stolower(key);

getline(cin, article);
stolower(article);

int m = 0;
for(int i = 0; i < article.length(); i++)
{
if(article[i] != ' ' && (article[i - 1] == ' ' || i == 0))
pos[m++] = i;
}
stringstream s_stream(article);

int first = 0, firstpos = 0, count = 0, charcount = 0;
int npass = 0;
while(s_stream >> word)
{
if(word == key)
{
if(!first)
{
firstpos = pos[npass];
first = 1;
}
count++;
}
npass++;
}
if(!first)
printf("%s\n", "-1");
else
printf("%d %d\n", count, firstpos);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  string stream include c