C++string类常用函数
来源:互联网 发布:今年淘宝生意不好做 编辑:程序博客网 时间:2024/06/04 18:59
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很详细。
- C++string类常用函数
- C++string类常用函数
- C++string类常用函数
- C++string类常用函数
- C++string类常用函数
- C++string类常用函数
- C++string类常用函数
- C++string类常用函数
- C++string 类常用函数
- C++string类常用函数
- C++string类常用函数
- C++string类常用函数
- C++string类常用函数
- C++STRING类常用函数
- C++string类常用函数
- C++string类常用函数
- C++STRING类常用函数
- C++string类常用函数
- [博主正在看]一代宗师[2013][中国][动作剧情]
- Orange'S(一) 第一、第二章 ubuntu安装bochs 并运行helloworld
- ebs启动脚本中的:jtffmctl.sh
- sql 多行转换为一行(STUFF及PIVOT的用法) ||SQL 合并列值和拆分列值
- select语句执行顺序
- C++string类常用函数
- 使用Git、Git GUI和TortoiseGit
- myEclipse的一些设置
- 2013.08
- 祝贺在CSDN上开通博客与空间
- Uninstall Adobe Photoshop with WindowsUninstaller.Org Removal Tips
- java导出pdf
- 电脑ip绑定,vm虚拟机上网u
- 如何设计一个LRU Cache?