C++ string 常用函数总结
2021-06-08 18:05
                         标签:下标   系统   使用   targe   运算   一个   str   构造   lan    头文件: 官方文档 输出: 使用  由此得到的  关于子串还有函数  举例如下: 输出: ?		函数  字符串连接 + 举例如下: 输出: 字典序比较: 使用下标  同字符数组。 使用迭代器访问 举例如下: 输出: 插入  其作用为在字符串  删除  其作用为从字符串  清空字符串  判断字符串是否为空  举例如下: 输出: 替换  其作用为替换  输出为: 查询  本函数用于在字符串  输出为: C++ string 常用函数总结 标签:下标   系统   使用   targe   运算   一个   str   构造   lan    原文地址:https://www.cnblogs.com/HOMEofLowell/p/14514041.html#include
[注]:文中关于个数的参数文档中为 size_type 型,更本质是 size_t  型,因为typedef size_t size_type,而 size_t 在不同系统内实现不同,大概为 unsigned int 型,为简便起见,本文均写为 int 型。另外,string 的许多函数都有各种重载,本文所写的只是较常用的。赋值
string 类型的变量可以直接赋值:string str = "hello world";		//可以直接赋值 
cout 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 123
23456
长度
string.size() 和 string.length() 均可返回本字符串长度,返回值类型为 int(size_t) 。运算符
string str1 = "abc", str2 = "def";
str = str1 + str2;
cout 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 开头插入: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  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!