(7)风色从零单排《C++ Primer》 string
2015-07-02 12:21
387 查看
初始化:
string s1 string s2(s1) string s2 = s1 string s3("value") string s3 = "value" string s4(n,'c')
读取未知个数的字符串
1)cincin读取字符串时,遇到leading whitespace(eg spaces,newlines,tabs)就会完成一次读取。
string word; while(cin>>word) cout<<word<<endl;
2)getlin()
当我们想整行读取时,可以使用getline,当遇到换行时完成一次读取。
string line; while(getline(cin,line)) cout<<line<<endl;
string操作
1)enpty和sizeempty()返回true,字符串是否为空
size()返回字符串个数,注意它的类型时一个unsigned类型,string::size_type因此,在比较时,要注意unsigned类型不要和负值比较。
auto len = line.size();//len has type string::size_type
2)字符串比较
==,当两个字符串有相同的字符内容时,返回真。
>,< 有三种情况
string str = "Hello"; string phrase = "Hello World"; string slang = "Hiya";
str<phrase , slang > phrase>str (i>e)
3)字符串相加
string s1 = "hello,", s2 = "world\n" string s3 = s1 +s2;//s3 is hello,world\n string s4 = s1 + ",";//ok string s5 = "hello" + ",";//error: no string operand string s6 = s1 + "," + "world";//ok string s7 = "hello" + "," + s2;//error can't add string literals
4)字符串访问
遍历每一个字符
for(auto c:str) cout << c << endl;
for(auto &c : s) c = toupper(c);
随机访问字符串
for(decltype(s.size())) index = 0;index != s.size() && !isspace(s[index]);++index) s[index] = toupper(s[index]);
const string hexdigits = "0123456789ABCDEF" string result; string::size_type n; while (cin >> n) if(n < hexdigits.size()) result += hexdigits ; cout << result << endl;
cctype Functions
需要引入cctype库。isalnum(c)
isalpha(c)
iscntrl(c)
isdigit(c)
islower(c)
isgraph(c)
isprint(c)
ispunct(c)
isspace(c)
isupper(c)
isxdigit(c)
tolower(c)
toupper(c)
相关文章推荐
- 给出年、月、日,计算该日是该年的第几天。
- C++ 排序函数 sort(),qsort()的用法
- C++ STL中Map的按Key排序和按Value排序
- C++学习:** 多重指针
- 用递归法将一个整数n转换成字符串
- C++sort函数的用法
- c++ 提升应用程序的权限
- 将字符串中最长的单词输出
- c语言中static用法总结
- C/C++中的输入与输出及如何读取一行文本
- 浅谈 C++ 中的 new/delete 和 new[]/delete[]
- 《C语言及程序设计》实践参考——随便改
- 《C语言及程序设计》实践项目——程序的多文件组织
- C++抽奖程序实现方法
- 《C语言及程序设计》程序阅读——程序的多文件组织
- c++11 & 14: unique_ptr shared_ptr std::make_unique(c++14)
- C++ Primer 学习笔记(1)——巧妙利用cin返回值为其左操作数的特点
- MFC,VC++中,CView类意外消失
- C++ Sort类成员的传递
- JNI初次使用---在C++中得到一系列圆并返回ArrayList