Code:
void test_string() {
string 初始化
string s0;//s0="", null string
string s1(5, 'a');//s1="aaaaa"
string s2(s1);//s2="aaaaa"
char* cStr = "Happy!";
string s3(cStr);//s3="Happy!", C 风格字符串赋值给string,直接赋值
string s4(cStr, 2);//s4="Ha", s(cp,n),参数1是C风格字符串,则是取前面n个元素
string s5("christomas");
string s6(s5, 2);//s6="ristomas", string s(s1, pos), 从位置pos开始到末尾的所有元素
string s7(s5, 0, 4);//s7="chri",string s(s1, pos, len),从位置pos开始到len个元素
// **** 基本操作都支持 s.func(pos, len) 或者 s.func(s1, pos, len) ****
//修改string
string str0 = "hello";
str0.insert(2, "ABC");//str0 = "heABCllo"; 在pos位置前插入string
string str1 = "Book";
string str_("XX");
str1.assign(str_);//str1 = "XX";//将str1替换为str_
//寻找子串
string str2 = "ABCDE";
string sub_s = str2.substr(1, 3);//sub_s = "BCD", s.substr(pos, n); 从位置pos 开始的n个元素
string sub_s1 = str2.substr(2);//sub_s1 = "CDE", s.substr(pos);
string sub_s2 = str2.substr();//sub_s2 = "ABCDE", 等于str2的副本
//追加和替换
string str3 = "test";
str3.append("__string");//str3="test__string"
str3.replace(4, 2, "++");//str3="test++string"
//字符串相加
string str4 = "Math";
char* cc = "Teacher";
str4.append(cc);//str4 = "MathTeacher",
string str5 = "Good ";
string str6 = str5 + cc;//str6="Good Teacher"; C风格字符串和string相加
//常用函数
string ss = "";
bool flag = ss.empty();//flag= true
ss = "House";
string::size_type size1 = ss.size();//size1=5, string::size_type unsigned 类型 ,与机器无关
char c1 = ss[0];//c1='H', 元素的随机访问
char c2 = ss.at(1);//c2='o'
string s_a = "What Fuck at";
string::size_type pos1 = s_a.find("at");//pos1=2,返回第一次匹配字符串的位置,如果没有则返回string::npos。
string::size_type pos11 = s_a.find("at",4);//pos11=10,s.find(str1, pos)从pos位置开始查找
string::size_type pos2 = s_a.rfind("at");//pos1=10, 从字符串末尾开始匹配字符串,并返回实际的位置
// find_first_of 函数最容易出错的地方是和find函数搞混。它最大的区别就是如果在一个字符串str1中查找另一个字符串str2,
// 如果str1中含有str2中的 任何字符 ,则就会查找成功,而find则不同;
string::size_type pos3 = s_a.find_first_of("tpy");//pos3=3
}
Demo1和Demo2来源于C++Primer第四版第九章习题
Demo1:
//Demo1:: 查找数字出现的位置
string testStr = "ab6P8mn50u";
string s_num = "0123456789";
string::size_type posGet = 0;
while ( (posGet = testStr.find_first_of(s_num, posGet)) != string::npos ) {
cout << "pos: " << posGet << " num is:" << testStr[posGet] << endl;
++posGet;
}
Demo2:
//Demo2:: 统计单词数量
{
string words = "This is a Book. We, all have, it: But, have, nothing! Good Bye.";
string table = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
string::size_type start_pos = 0, end_pos=0;
string::size_type findPos = 0;
while (start_pos < words.size()) {
findPos = words.find_first_of(table, start_pos);
end_pos = words.find_first_not_of(table, start_pos);
if (findPos > end_pos) {
++start_pos;
continue;
}
if (findPos== string::npos || end_pos == string::npos) {
break;
}
int len = end_pos - findPos;
//获取单词
string getWord = words.substr(start_pos, len);
cout << "words:" << getWord << endl;
start_pos = end_pos + 1;
}
}