C++string类常用函数

string类有很多函数

 

最近在看C++ primer 加上最近项目用了很多“容器”,多看了下。

今天在做里面一道Exercise  编写程序统计并输出所读入的单词出现的次数。  惭愧  ,我做的时候理解成了字母出现的次数,所以就写成统计一段字符串中出现的字母和其次数。

 

逻辑很简单:

声明一个    map<字母 , 次数>  word_count;   

将字符串的字母一个个的读出 假设为word变量

然后 word_count[word]++  实现出现一个字母就加一;

 

但是在写的时候我们可以多想想:

次数的类型用int 没什么说的,但是字母的类型就可以有多种了 可以是char ,可以是char*, 也可以是string类型。

因为最近的项目 让我知道用string保险一些,当然在这个程序里 效果一样。

好的 现在写成map<string ,int >word_count;

	map<string,int>  word_count;
	string  sentence;
	cin>>sentence;
	int size=sentence.size();
	cout<<"sentence size is "<<size<<endl;
	char word[2]={0};
	map<string,int >::iterator  iter;
	for(int i=0;i<size;i++)
	{
		strncpy(word,sentence.data()+i,1);
		++word_count[word];
		//cout<<sentence.data()+i<<endl;
	}
	//cout<<sentence<<endl;
	//cout<<word_count.size()<<endl;
	for(iter=word_count.begin();iter!=word_count.end();iter++)
	{
		cout<<iter->first<< ","<<iter->second <<endl;
	}

重点在这么来取字符串的变量

我发现 用 sentence.data()得到的是我想要的结果  即返回字符数组 再用   sentence.data()+i   就可以无错误的访问下一个字母。

但是用 sentence.c_str()却会得到一些乱码。c_str()是返回字符串首字母地址的呀?为什么会错了。MSDN 上说:  returns a pointer to a nonmodifiable C string constructed by adding a terminating null element,不能修饰的结尾带NULL的字符串。

2.

如果将定义关联容器map<char,int>  word_count;

主要代码如下:

map<char,int>  word_count;
	string  sentence;
	cin>>sentence;
	int size=sentence.size();
	cout<<"sentence size is "<<size<<endl;
	//char word[2]={0};
	map<char,int >::iterator  iter;
	for(int i=0;i<size;i++)
	{
		//strncpy(word,sentence.at(i),1);
		++word_count[sentence.at(i)];
		//cout<<sentence.data()+i<<endl;
	}
	//cout<<sentence<<endl;
	//cout<<word_count.size()<<endl;
	for(iter=word_count.begin();iter!=word_count.end();iter++)
	{
		cout<<iter->first<< ","<<iter->second <<endl;
	}


 

用sentence.at(i)  i表示位置  它返回的值就是个char型  !

 

网上有篇讲C++string类函数的帖http://www.cppblog.com/lmlf001/archive/2006/04/19/5883.html很详细。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值