9.求子串
string substr(size_t pos = 0, size_t len = npos) const;
substr得到当前串从pos位置开始,长度为len范围内的子串,参数采用默认值则相当于复制原串。
10.字符串拼接
使用“+”可以方便实现拼接两个字符串:
string s1 = "Hello";
string s2 = "Tom";
string s3 = s1 + " " + s2 + "!";
不过,由于字符串不是内置类型,所以加号两端,必须至少有一个是std::string类型,不支持直接相加两个C风格字符串:
//不支持,因为相加过程和std::string无关
string s = "Hello" + "Tom!";
string s1 = string("Hello") + " Tom!";//支持
string s2 = "Hello" + string(" Tom!");//支持
自加操作“+=”也有意义直观的支持
string s3 = "Hello";
s3 += " Tom!";
使用+和+=拼接字符串,虽然方便,但效率不高,另外也不方便拼接其他类型,比如整数,更常用的方法是使用标准库的内存字符流,std::stringstream。
#include <sstream>
string s1 = "How";
string s2 = "old";
char const* s3 = "are";
int age = 9;
std::stringstream ss;
ss << s1 << ' ' << s2 << " "
<< s3 << " you? I am " << age << '.';
string result = ss.str();
cout << result << endl;