《c++ primer》3.2 string 小结

1. 头文件

#include<string>
using std::string;

 

当然,如果打了

using namespace std;

就不需要再打

using std::string;

按我理解,namespace std 就包括了string 相关的所有声明了。

2. 声明string变量

string s1; // 内容为空的 string
string s2 = s1;
string s3 = "hiya";
string s4(10,'c'); // cccccccccc
string s5(s4);
string s6("hiya");

3. 对string的操作

os << s // os: output stream
is >> s // is: input stream
getline(is, s) // read a line of input
s.empty() // returns true if empty, otherwise returns false
s.size() // returns size of s, i.e. number of characters
s[n] // returns the nth character, starting from 0
s1+s2 // 两个string连缀得到一个更长的string
s1=s2 // copy赋值
s1==s2 // 完全相同:长度相等,字符相同
s1!=s2 // 有不同之处
<,<=,>,>= // ①首先判断,谁长就谁大 ②如果一样长,按字典顺序排序

4. size_type

为了提供一个对机器无依赖的类型,他们自定义了size_type类型,size返还的就是一个size_type类型。

size_type类型是一个unsigned、可以是足够大的正整数的类型。

所以,不要把 signed 类型与 size返还结果放在一起运算,避免负整数带来的问题。

5. Range-Based for

这好像是c++ 11的特性。

for (declaration : expression)
    statement

比如

string str("some string");
for( auto c : str)    // for every char in str
    cout<<c<<endl;

6. 判断字符值的函数

isalnum(c)       true if c is a letter or number
isalpha(c)        true if c is a letter
iscntrl(c)        true if c is a control letter
islower(c)        true if c is a lower-case letter
tolower(c)        if c is uppercase, returns lowercase, otherwise returns unchanged

7. 下标

string s("some string");
if(!s.empty())
    s[0]=toupper(s[0]);
cout<<s<<endl;

下标从0开始,但要自己注意不要越界,否则结果不可预测。

 

posted on 2019-10-08 04:35  luyi07  阅读(198)  评论(0编辑  收藏  举报

导航