C++ string 常用函数总结
头文件:#include<string>
[注]:文中关于个数的参数文档中为 size_type 型,更本质是 size_t 型,因为typedef size_t size_type,而 size_t 在不同系统内实现不同,大概为 unsigned int 型,为简便起见,本文均写为 int 型。另外,string 的许多函数都有各种重载,本文所写的只是较常用的。
赋值
-
string类型的变量可以直接赋值:string str = "hello world"; //可以直接赋值 cout << str << endl; //string 不支持 C 语言,因此输出只能使用 cout 不能使用 printf输出:
hello world -
使用
string的构造函数来实现拷贝的效果:string substr = string(string str, int start, int num);由此得到的
substr是截取字符串str从start起num个字符。 -
关于子串还有函数
substr(int start, int num),其效果同上。举例如下:
//返回子字符串 substr string str = "012345678"; string substr = str.substr(1,3); cout << substr << endl; substr = string(str, 2, 5); cout << substr << endl;输出:
123 23456
长度
函数 string.size() 和 string.length() 均可返回本字符串长度,返回值类型为 int(size_t) 。
运算符
-
字符串连接 +
举例如下:
string str1 = "abc", str2 = "def"; str = str1 + str2; cout << str << endl;输出:
abcdef -
字典序比较:
> < >= <= != ==
遍历/访问
-
使用下标
[]访问同字符数组。
-
使用迭代器访问
举例如下:
string str = "hello world"; //可以直接赋值 printf("按元素下标访问:%c %c\n", str[0], str[str.size()-1]); //可以按照元素下标访问 //通过迭代器 iterator 访问 迭代器类似于指针 printf("迭代器访问str:\t"); for(string::iterator it = str.begin(); it != str.end(); ++it) { printf("%c ", *it); } printf("\n"); printf("str.begin() = #%c#", *str.begin()); //迭代器类似于指针 要加 * printf("str.end() = #%c#", *str.end());输出:
按元素下标访问:h d 迭代器访问str: h e l l o w o r l d str.begin() = #h#str.end() = # #
增删改查
-
插入
string.insert(int pos, string str)其作用为在字符串
string第pos个字符处插入字符串str。 -
删除
string.erase(int pos, int len)其作用为从字符串
string第pos个字符处删除len个字符。 -
清空字符串
string.clear() -
判断字符串是否为空
string.empty()举例如下:
string str = "hello world"; //插入 str.insert(0, "Start "); //在开头插入 cout << "开头插入:" << str << endl; str.insert(str.size(), " End."); //在末尾插入 cout << "末尾插入:" << str << endl; str.insert(6, "Middle "); //在中间插入 cout << "中间插入:" << str << endl; //删除 str.erase(0,1); //删除 从第 0 位开始的 1 个 cout << "删除第一个元素:" << str << endl; str.erase(0, 2); //删除 从第 0 位开始的 2 个 cout << "删除前两个元素:" << str << endl; cout << str.empty() << endl; str.clear(); //清空 cout << str.empty() << endl;输出:
开头插入:Start hello world 末尾插入:Start hello world End. 中间插入:Start Middle hello world End. 删除第一个元素:tart Middle hello world End. 删除前两个元素:rt Middle hello world End. 0 1 -
替换
string.replace(int pos, int len, string temp)其作用为替换
string字符串从pos起len个字符为 字符串temp。举例如下:string str = "123456"; string temp = "abc"; str.replace(0, 1, temp); cout << str << endl;输出为:
abc23456 -
查询
string.find()本函数用于在字符串
string中寻找字符或字符串,若找到则返回其第一个字符所在下标位置,若没有对应字符或字符串,则返回string.npos,即-1。举例如下:string str = "hello world"; int found = str.find("world"); if(found != str.npos) //npos = -1 { printf("%d\n", found); } found = str.find('l'); if(found != str.npos) { printf("%d\n", found); } found = str.find('.'); if(found == str.npos) printf("Not found!\n");输出为:
6 2 Not found!

浙公网安备 33010602011771号