c++之string字符串常用函数
一、头文件
#include<string>
二、常用函数
1.查找 函数find、rfind 查找子串或单个字符
find 从前向后查找第一个
str.find(“ab”);
str.find(‘c’);
遍历字符串查找子串"abc"【字符’c’】,返回找到的下标位置
str.find(“ab”, pos);
从当前字符串的pos索引位置开始,查找子串/单个字符,返回找到的位置索引
rfind 从后往前查找最后一个
str.rfind(“ab”, pos);
从当前字符串的pos索引位置开始,反向查找子串,返回找到的位置索引
2.插入 函数 insert
str.insert(index,string);
从下标index开始添加字符串string
str.insert(index,string,3);
从下标index开始添加字符串string的前3个字符串,即下标3之前,[0,2]的字符
str.insert(index,string,1,3);
从下标index开始添加字符串string下标[1,3]的字符
3.追加 函数 append、+
str.append(“abc”);
在字符串末尾追加字符串”abc”
4.替换 函数 replace
str.replace(开始替换下标,替换字符个数,新字符串);
str.replace(2,4,”hi”);
str.replace(2,4,”abcd”,3);
最后的数字3,表示只用新字符串的前3个进行替换
str1.replace(pos,n,n1,char c);
将当前字符串从pos索引开始的n个字符,替换成n1个字符c str1.replace(str1.size()-1,1,1,’.’);
5.切割 函数 substr
str.substr(index);
返回下标index及以后的子串
str2=str1.substr(index,len);
返回从下标index到切割长度为len的子字符串
6.删除 函数 erase
str.erase(index);
删除下标index及以后的字符
str.erase(下标,1);
删除下标为index的字符
str.erase(开始下标index,删除长度/字符个数len);
7.字符大小写转换 函数 tolower(单个字符)、toupper(单个字符)
tolower(char c);
小写
toupper(char c);
大写
- 交换 函数 swap
swap(str1,str2);
- 其他 函数
str.size();
返回字符串大小
str.length();
返回字符串的长度
str.resize(len);
字符串重新设置长度
str.empty();
判断字符串是否为空,空返回1,否则0
str.clear()
清空字符串
str[i];
取下标为i的字符
str.at(index);
取下标为index的字符
三、常用函数使用
#include<iostream>
#include<string>
using namespace std;
int main()
{
string s="hello,world";
//查找 find、rfind
cout<<s.find('l')<<endl;
cout<<s.find("world")<<endl;//返回首字母w所在下标
cout<<s.find('l',3)<<endl;//查找位置包括下标3
cout<<s.rfind('l')<<endl;
//插入函数insert
s.insert(s.length(),"...");
cout<<s<<endl;
//追加函数append
s.append("why");
cout<<s<<endl;
//替换函数replace
s.replace(11,6,"!");
cout<<s<<endl;
//切割函数substr
cout<<s.substr(6,5)<<endl;//字符串切割产生一个新的子串,原来的字符串并未改变
cout<<s<<endl;
//删除函数erase
s.erase(0,1);
cout<<s<<endl;
s.erase(0,5);
cout<<s<<endl;
//大小写转换toupper(ch)、tolower(ch)
for(int i=0;i<s.length();i++)
{
s[i]=toupper(s[i]);
}
cout<<s<<endl;
//交换函数swap
string str1="abcd";
string str2="123";
swap(str1,str2);
cout<<str1<<endl;
//其他函数
cout<<s.at(2)<<endl;
s.clear();
cout<<s.empty();
return 0;
}
}
运行结果