string
3 minute read
string
定义和初始化 string
对象
string s4(10,'c'); //s4 == "cccccccccc";
string s2(s1) == string s2 = s1;
string s3("value") == string s3 = "value";
string s4(n,'c'); //把s4初始化为由连续的 n 个字符 c 组成的串.
string s5 = "hiya";//拷贝初始化
string s6("hiya"); //直接初始化
string s7(10,'c');//直接初始化
string
对象上的操作
s.empty();// s 为空返回 true
s1 == s2;// s1 和 s2 中所含字符完全一致返回 true, 对大小写敏感
s1 != s2;
//<, <=, >, >= 利用字符在字典中的顺序进行比较,且对字母的大小写敏感
string::size_type
类型
string
类及其他大多数标准库类型都定义了几种配套的类型,这些类型体现了 标准库类型和机器类型无关的特性 类型 size_type
即是其中的一种,在具体使用的时候,通过 作用域操作符 来表明 size_type
是在类 string
中定义的。
这里可以使用 auto
来获取 size_type
的类型,对于很多不知类型的变量,要记得使用 auto
.
auto len = line.size(); //len 的类型为 string::size_type
字面值和 string
对象相加
当把 string
对象和字符字面值及字符串字面值混在一条语句中使用时,必须保证每个加法运算符 (+) 的两侧的运算对象至少有一个是 string
.
string s4 = s1 + ","; //把一个 string 对象和一个字面值相加.
string s5 = "hello" + ","; //error: 两个运算对象都不是 string
//right: 每个加法运算符都有一个对象时 string
string s6 = s1 + "," + "world"; //right
string s7 = "hello" + "," + s2; //error: 不能把字面值直接相加
string s6 = (s1 + ",") + "world"; //s1 + "," 后组成了一个新的字符串,再和 "world" 相加
string s7 = ("hello" + ",")+s1; //"hello" + "," 错了
处理 string
对象中的字符
基于范围的 for
语句
for (declaration : expression)
statement;
这里通过 auto
让编译器决定 c
的类型
string str("some string");
for(auto c : str)
cout << c << endl;
这里通过 decltype
关键字,声明计数变量 punct_cnt
,它的类型是 s.size()
函数返回值的类型,也就是 string::size_type
string s("Hello World!");
decltype(s.size()) punct_cnt = 0;
for(auto c : s)
if(ispunc(c))
++punc_cnt;
cout<<punct_cnt
<<" punctuation characters in "<< s <<endl;
others
toupper
可以将当前字符改为大写形式
tolower
可以将当前字符改为小写形式
对 string
进行索引访问(及下标访问)时,要避免越界,以及 string
是否为空,此时访问 string[0]
即为非法.
迭代器明天再补充,又是两点才睡的一天.