string s1; //默认初始化,是个空串。 string s2(s1); //s2是s1的副本 string s2 = s1; //等同于 string s2(s1) string s3 = ("abc"); //直接赋值 string s3("abc"); //等同于 stirng s3 = ("abc") string s4(4 , 'a'); //初始化为连续4个a组成的串
string s1 = "abc"; //利用 += 拼接 s1 += "def"; // s1 = "abcdef" string s2 = "def"; s1 += s2; //利用 append 拼接 s1.append("def"); // s1 = "abcdef" s1.append("defgh",3); // 对字符串 "defgh" 前 3 个 追加到 s1 后面 string s3 = "defgh"; s1.append(s3 , 0 , 3); // 把数组 s3 从第 0 个位置向后 3 个字符追加到s1 上
查找一段字符串是否存在,若找到返回下标,找不到返回-1。find是从左向右查找,rfind是从右向左查找。
string s1 = "abcdef"; int pos = s1.find("def"); // 如果对s1进行查找 "def" 找的到 右式值为其第一个字符的下标 找不到 右式值为 -1 if(pos == -1) { cout << "找不到此字符串"; } else { cout << "找到了字符串,下标是:" << pos; }
对字符串指定的位置进行替换操作。
string s1 = "abcdef"; s1.replace(2 , 3 ,"ppp"); //对于 s1 从下标为 2 的位置(包括2的位置)共换 3 个字符换成 "ppp" "abpppf" //有趣的是 如果 "ppp" 变成 "pppp" 还是换 3 个字符, 会变成 abppppf ,确实只替换了 3 个字符,但也把多的一个 'p' 加上了
按位比较ASCII码值。
string s1 = "abc"; string s2 = "def"; int p = s1.compare(s2); // 若 p = 0 两字符串相同, 若 p = 1 s1 大 , 若 p = -1 s2 大
string s1 = "abc"; //读 //[] for(int i = 0 ; i < s1.size() ; i++) { cout << s1[i] << ' '; } //at for(int i = 0 ; i < s1.size() ; i++) { cout << s1.at(i)<< ' '; }, //写 s1[0] = 'w'; s1.at(0) = 'w';
string s1 = "hello"; //插入 s1.insert( 2 , "asd"); //从下标为 2 的地方(包括2)插入内容为 "asd" 得到 heasdllo //删除 s1.erase( 2 , 3); //从下标为 2 的地方(包括2)删除后 3 个字符 得到 hello
string s1 = "abcdefg"; string s2 = s1.substr(2 , 3); //将s1的子串 从下标为 2 的地方(包括2)开始 后 3 个字符拷贝到 s2 中去