去除字符串标点 + 泛型算法使用

问题:读取一个文件(含标点),统计长度小于4的单词个数,并按长度顺序输出,重复单词只输出一次。
考查:去除字符串标点 + 泛型算法使用
思路:1.获取每个单词,存入到vector中去——考查:去除字符串标点
 2.剔除重复单词,——考查:泛型算法使用
一、去除标点符号
1.读取一个含有标点符号的文件,
2.使用 startPos=str.find_first_not_of(separators,endPos),寻找到第一个字母;
3.使用   endPos=endPos=str.find_first_of(separators,startPos),寻找到从startPos开始后的第一个字母
4.对 startPos和endPos进行判断,确认纯字母的字符串的长度wordLen;
5.使用substr()函数求得该纯字母子串。word=str.substr(startPos,wordLen);
注意:对于hello,nihao,这种字符串,可能一个string中存在两个单词,故需要使用while循环逐个挑出来。


二、使用泛型算法
1. 使用sort(svec.begin(),svec.end())对字符串进行排序,保证相同的字符串处于相邻位置。

2. 使用unique()函数将重复单词置于尾部。
vector<string>::iterator end_unique=unique(svec.begin(),svec.end());


3. 剔除掉末尾的单词。svec.erase(end_unique,svec.end());


4. 重新设计排序规则,使剩余的不重复单词按照长短进行排序。

stable_sort(svec.begin(), svec.end() , isShort);


代码:

#include<iostream>
#include<fstream>
#include<string>
#include<vector>
#include<algorithm>

using namespace std;


isShort(const string &s1,const string &s2){//注意参数,const 和&
	return s1.size() < s2.size();
}

bool GT4(const string &s){
	return s.size() >= 4;
}

int main(){
	string str;
	ifstream infile;
	infile.open("input.txt") ;

	string separators("	f
v:,.");
	string::size_type startPos=0,endPos=0;
	string word;
	string::size_type wordLen=0;

	vector<string> svec;

	while(infile>>str){
		//svec.push_back(str);只有这一句,会使得字符串将标点符号也输入到str中去。

		///////////去掉输入的字符串中的标点符号,将纯字符串push到vector中去///////////////////////////////////////////////////////
		startPos=0,endPos=0;
		while( (startPos=str.find_first_not_of(separators,endPos) )
			!=string::npos ) {

			endPos=str.find_first_of(separators,startPos);
			if(endPos==string::npos)
				wordLen=str.size()-startPos;
			else
				wordLen=endPos-startPos;
			word=str.substr(startPos,wordLen);
			
			svec.push_back(word);
		}
		///////////去掉输入的字符串中的标点符号///////////////////////////////////////////////////////
	}

	sort(svec.begin(),svec.end());
	
	vector<string>::iterator end_unique=unique(svec.begin(),svec.end());

	svec.erase(end_unique,svec.end());

	stable_sort(svec.begin(), svec.end() , isShort);

	vector<string>::size_type n=count_if(svec.begin(), svec.end(), GT4 );
	cout<<n<<" word(s) length greater than 4"<<endl;

	for(vector<string>::iterator iter=svec.begin();
	iter!=svec.end();++iter){
		cout<<*iter<<endl;
	}

	cout<<endl;

	

	return 0;
}


原文地址:https://www.cnblogs.com/sjw1357/p/3864026.html