String类在开发过程中经常用到,这里来总结一下。
1.声明与初始化
std::string str;//声明
std::string str = "Hello, World!";//初始化
2.连接
std::string str1 = "Hello, ";
std::string str2 = "World!";
std::string result = str1 + str2;
输出为“Hello,World!”
3.常用函数
3.1 返回字符串的字符数——size()
使用:str.size()
3.2 判断字符串是否为空——empty()
使用: str.empty()
3.3 访问字符串中指定位置的字符——at()
使用:str.st(1);//访问str第1个字符
3.4 返回从指定位置开始的子字符串——substr()
使用:std::string sub = str.substr(0, 5);//返回str1下标从0开始长度为5的子字符串
3.5 查找子字符串在字符串中的位置——find()
使用:str.find("pid");//返回str1中第一次出现“pid”字符的位置
str.find("pid",1);//寻找从1开始(包括1处字符)匹配“pid”字符的位置。
3.6 找到目标字符在字符串中第一次出现和最后一次出现的位置——find_first_of() 和 find_last_of()
使用:str.find_first_of(str1) 和 str.find_last_of(str1)
3.7 从字符串末尾开始查找子字符串的位置——rfind()
使用:str.rfind("pid");//从后开始查找str中“pid”第一次出现的位置
3.8 替换字符串中的部分内容——replace()
使用:str.replace(pos, length, "pid");//把str中从pos开始长度为length的字符串替换为“pid”
3.9 在字符串末尾添加内容——append()
使用:str.append(" more");//在str1末尾添加字符串“more”
3.10 在指定位置插入内容—insert()
使用:str.insert(pos, "in");//在str末尾添加字符串“in”
3.11 删除指定位置的字符或子字符串——earse()
使用: str.erase(pos, length);//删除从pos位置开始的长度为length的字符串
3.12 清空字符串——clear()
使用:str.clear()
3.13 比较两个字符串——compare()
使用:int result = str.compare("other");//比较str1与“other”,若相等,result=0。