练习下C++ STL中std::string类的常用方法,方便以后查阅。
如有不正确的地方,请读者及时指正,欢迎转载,谢谢!
#include <assert.h>
#include <string>
//测试std::string
inline void testString()
{
//构造string,编译器会对下面语句进行优化,不同编译器调用过程可能不一样,VC下调用情况如下:
std::string str1("hello Jim, welcome to china."); //直接初始化,调用构造函数
std::string str2(str1); //直接初始化,调用拷贝构造函数
std::string str3 = "hello Jim, welcome to china."; //拷贝初始化,调用构造函数
std::string str4 = str3; //拷贝初始化,调用拷贝构造函数
std::string str5 = std::string("hello Jim, welcome to china."); //同str3
//字符串查找
//查找字符串Jim第一次出现的位置
std::size_t pos = str1.find("Jim");
assert(pos == 6);
//查找字符','第一次出现的位置
pos = str1.find(',');
assert(pos == 9);
//反向查找字符串Jim第一次出现的位置
pos = str1.rfind("Jim");
assert(pos == 6);
//查找,:.中的某个字符第一次出现的位置
pos = str1.find_first_of(",:.");
assert(pos == 9);
//查找,:.中的某个字符最后一次出现的位置
pos = str1.find_last_of(",:.");
assert(pos == 27);
//字符串操作
//substr截取子串开始直到Jim,左闭右开
std::string frontstr = str1.substr(0, str1.find("Jim"));
assert(frontstr == "hello ");
//substr截取子串Jim开始直到最后,左闭右开
std::string backstr = str1.substr(str1.find("Jim"), str1.size());
assert(backstr == "Jim, welcome to china.");
//重新拼接字符串
str1 = frontstr.append(backstr);
assert(str1=="hello Jim, welcome to china.");
//替换字符串Jim为Jack
str1.replace(str1.find("Jim"), strlen("Jim"), "Jack");
//删除字符串hello和后面的空格
str1.erase(str1.find("hello "), strlen("hello "));
//交互teststr和teststr2的值
str1.swap(str2);
assert(str1=="hello Jim, welcome to china.");
assert(str2=="Jack, welcome to china.");
//比较字符串str1和str2的大小,大于返回1,小于返回-1,==返回0
int compare = str1.compare(str2);
assert(compare == 1); //小写字母的ascii码大于大写字母
//字符串插入insert
str1.insert(str1.find("Jim")+strlen("Jim"), " Green");
assert(str1 == "hello Jim Green, welcome to china.");
return;
}