1 string
string内部含有一个char*字符串
2 string构造方式
- 无参构造
string str;
- 字符串构造
string str("abcd");
- 拷贝构造
- n个相同字符
string str(10, 'k'); //初始化为10个k
3 string赋值操作
可以有以下操作:
void string_test() {string str1;str1 = "str1";cout << "str1 = " << str1 << endl;string str2 = str1;cout << "str2 = " << str2 << endl;string str3 = "a";cout << "str3 = " << str3 << endl;string str4;str4.assign("str4");cout << "str4 = " << str4 << endl;string str5;str5.assign("123456789", 5);cout << "str5 = " << str5 << endl;string str6;str6.assign(str5);cout << "str6 = " << str6 << endl;string str7;str7.assign(10, 'k');cout << "str7 = " << str7 << endl;
}
结果为:
4 string拼接
可以使用的是 += 以及append, 例子如下:
void string_test1() {string str1 = "str1";str1 += "str";cout << "str1 = " << str1 << endl;str1 = "str1";str1 += 's';cout << "str1 = " << str1 << endl;str1 = "str1";string str2 = "str2";str1 += str2;cout << "str1 = " << str1 << endl;str1 = "str1";str1.append("str");cout << "str1 = " << str1 << endl;str1 = "str1";str1.append(str2);cout << "str1 = " << str1 << endl;str1 = "str1";str1.append("abcdefg", 4); //拼前四个字符cout << "str1 = " << str1 << endl;str1 = "str1";str1.append("0123456789", 2, 3); //从第二(从0开始数)个字符开始拼三个字符cout << "str1 = " << str1 << endl;str1 = "str1";
}
5 查找和替换
find测试:
void string_find_test() {string str1 = "abcdefg";int position = str1.find("de", 2); //find有两个参数, 第一个是要查找的字符cout << "position: " << position << endl; //或者子串, 第二个参数是开始查找的位置,position = str1.find("df", 2); //第二个参数的默认值为0,返回值是找到的cout << "position: " << position << endl; //第一个子串起始位置的下标,如果未找到就position = str1.rfind("de", 2); //返回-1, rfind跟find的区别是:rfindcout << "position: " << position << endl; //是从右向左查找.
}
替换测试:
void string_replace_test() {string str1 = "abcdefg";str1.replace(1, 3, "1111"); //从下标1起, 3个字符替换为"1111"cout << "str1: " << str1 << endl;
}
6 字符串对比
如下测试代码:
void string_compare_test() {string str1 = "abcdefg";string str2 = "abcdefg";if (str1.compare(str2) == 0) {cout << "str1 = str2" << endl;} else if (str1.compare(str2) > 0) {cout << "str1 > str2" << endl;} else if (str1.compare(str2) < 0) {cout << "str1 < str2" << endl;}
}
此时compare是比较字符串的每一位, 如果每一位都想等, 那么就相等, 如果前面的字符的ASCII码值大于后面的, 那么就返回 >0, 否则小于0. 此时因为str1和str2都是"abcdefg", 所以返回的是0:
当string str1 = "abadefg", string str2 = "abcdefg"时, 结果为:
当string str1 = "abcdefg", string str2 = "abcaefg"时, 结果为:
7 对字符插入删除操作
如下代码:
void string_insert_delete_test() {string str1 = "abcdefg";str1.insert(1, "000");cout << str1 << endl;str1.erase(1, 3);cout << str1 << endl;
}
结果:
8 取子串
void string_substring_test() {string str1 = "abcdefg";string str2 = str1.substr(1, 3);cout << str2 << endl;
}
结果:
扩展用途如下:
void string_find_test() {string str1 = "xiaoming@163.com";int position = str1.find('@');string username = str1.substr(0, position);cout << "username: " << username << endl;
}
结果为:
9 字符串分割 strtok_r
函数原型:
char *strtok_r(char *str, const char *delim, char **saveptr);
其中:
- char *str 被分割字符串(如果传入NULL, 则直接分割最后一个参数, 也就是saveptr)
- const char *delim 分隔符,也是个字符串指针
- char **saveptr 一个供内部使用的指针,用于保存上次分割剩下的字串