string类型
//初始化
string s1;
string s2 = s1;
string s3 = "hiya";
string s4(5, 'C'); //s4内容为CCCCC
string操作
| 方法 | 作用 |
|---|---|
| os<<s | 将s写到输出流中os中,并返回os |
| is>>s | 从is中读取字符串赋值给s,字符串以空格分隔,返回is |
| getline(is,s) | 从is中读取一行,赋值给s |
| s.empty() | s为空返回true,否则返回false |
| s.size() | 返回s中的字符的个数 |
易错点
s1 = "hello";
st = "world";
string s2 = s1 + ", " + "world";
string s3 = "hello" + ", " + st; //错误
- s1 + ", "是string对象,+"world"是正确操作
- "hello" + ", "是字符串字面值,字符串字面值不能直接相加
遍历string
string str("Hello world");
for(auto s:str) {
cout<<s<<endl;
}
string str("Hello world");
for(auto &s:str) {
cout<<s<<endl;
}
判断类型
| 方法 | 作用 |
|---|---|
| isalnum(c) | 当c是字母或数字时为真 |
| isalpha(c) | 当c为字母时为真 |
| iscntrl(c) | 当c为控制字符时为真 |
| isdigit(c) | 当c为数字时为真 |
| isgraph(c) | 当c不为空格,但是可打印字符时 |
| islower(c) | 当c为小写字母时为真 |
| isupper(c) | 当c为大写字母时为真 |
| tolower(c) | 将c转化为小写字母 |
| toupper(c) | 将c转化为大写字母 |
for(decltype(s.size()) index = 0;
index != s.size() && isspace(s[index]); ++index)
s[index] = toupper(s[index]);