前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >统计字符串中的单词数目

统计字符串中的单词数目

作者头像
_gongluck
发布2018-03-08 17:26:44
1.6K0
发布2018-03-08 17:26:44
举报
//统计字符串中的单词数目——统计字符串中单词的数目,更复杂的话从一个文本中读出字符串并生成单词数目统计结果。
/*
Test my2test,12test...?tesst
hehe,dsf..e3234...242haha
*/
//输出结果9
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int	CountWords(char* filename)
{
	ifstream file(filename, ios::in);
	if (!file.is_open())
		return -1;
	string word;
	int count = 0;
	int size = 0;
	int index = 0;
	int preindex = -1;

	while (file >> word)
	{
		for (index = 0, preindex = -1, size = word.size(); index < size; ++index)
		{
			index = word.find_first_of("0123456789,.?", index);
			if (index == string::npos)//查找结束
			{
				if (preindex == -1 || size > preindex + 1)
				{
					++count;
					break;
				}
			}
			else
			{
				if (preindex == -1 && index != 0 || index > preindex + 1)
				{
					++count;
				}
				preindex = index;
			}
		}
	}
	return count;
}

int main(int argc, char* argv[])
{

	cout << CountWords("D:/test.txt") << endl;

	system("pause");
	return 0;
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017年06月26日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档