使用C++,统计一段字符串或是文章中,有多少个不同的单词。

eg:字符串"I love you"

输出结果3

字符串"I love you you"

输出结果3

函数func1(string str) 统计个数

main函数测试

#include <iostream>
#include<string>
#include <set>
using namespace std;
void fun1(string str){
    int L=str.length();
	int i=0;
	string words="";
    //用set存储 单词
	set <string> cnt;
	while(i<L)
	{
	if(str[i]>='A'&&str[i]<='Z'||str[i]>='a'&&str[i]<='z')
	{
	    words.push_back(str[i]);
	}
    //将单词放入set中
	if(str[i]==' '||i==L-1)
	{      
        if(words.size()!=0)
	    cnt.insert(words);
	    words.clear();
	}
	i++;
	}
    //set长度即为单词的去重个数
	cout<<cnt.size()<<endl;
}
int main() {
	string str="I love you you";
	fun1(str);
}

输出结果

猜你喜欢

转载自blog.csdn.net/af2251337/article/details/83023518
今日推荐