3.1.5 string查找和替换
查找:查找指定字符串是否存在
替换:在指定的位置替换字符串
函数原型:
1 int find(const string &str,int pos=0) const;//查找str第一次出现位置,从pos开始查找
2 int find(const char *s,int pos=0) const;//查找s第一次出现位置,从pos开始查找
3 int find(const char *s,int pos,int n) const;//从pos位置查找s的前n个字符第一次出现位置
4 int find(const char c,int pos=0) const;//查找字符c第一次出现位置
5 int rfind(const string &str,int pos=npos) const;//查找str最后一次出现位置,从pos开始查找
6 int rfind(const char *s,int pos=npos) const;//查找s最后一次出现位置,从pos开始查找
7 int rfind(const char *s,int pos,int n) const;//从pos位置查找s的前n个字符最后一次出现位置
8 int rfind(const char c,int pos=0) const;//查找字符c最后一次出现位置
9 string &replace(int pos,int n,const string &str);//替换从pos开始n个字符为字符串str
10 string &replace(int pos,int n,const char *s);//替换从pos开始n个字符为字符串s
示例:
void test01()
{
string str1 = "abcdefgde";
int pos=str1.find("de");
if (pos == -1)
{
cout << "未找到字符串" << endl;
}
else
{
cout << "找到字符串,pos= " << pos << endl;//结果为3
}
//rfind和find区别
//rfind从右向左查找 find从左往右查找
pos=str1.rfind("de");
if (pos == -1)
{
cout << "未找到字符串" << endl;
}
else
{
cout << "找到字符串,pos= " << pos << endl;//结果为7
}
}
void test02()
{
string str1 = "abcdefgde";
str1.replace(1, 3, "1111");
cout << "str1= " << str1 << endl;//str1=a1111efgde
}
3.1.6 string字符串比较
比较方式:按照字符的ASCII码进行对比
= 返回 0
> 返回 1
< 返回-1
函数原型:
int compare(const string &s) const;
int compare(cost char *s) const;
3.1.7 string字符存取
string中单个字符存取方式有两种:
char &operator[](int n);//通过[]方式取字符
char &at(int n);//通过at方式获取字符
示例:
void test01()
{
string str = "hello";
for (int i = 0; i < str.size(); ++i)
{
//cout << str[i] <<" ";
cout << str.at(i) << " ";
}
cout << endl;
str[0] = 'x';//str = xello
str.at(1) = 'x';//str = xxllo
}
3.1.8 string插入和删除
函数模型:
1 string &insert(int pos, const char *s);
2 string &insert(int pos, const string &s);
3 string &insert(int pos, int n, char c);//在指定位置插入n个字符c
4 string &erase(int pos, it n=npos);//删除从pos开始的n个字符
示例:
void test01()
{
string str = "hello";
str.insert(1, "111");//从第一个位置处插入
str.erase(1, 3);//从第一个位置处删除
}
注意:下标从0开始
3.1.9 string 子串
功能:从字符串中获取想要的子串
函数原型:
string substr(int pos=0,int n=npos) const;//返回由pos开始的n个字符组成的字符串
示例:
//应用
void test02()
{
string email = "celina@163.com";
int pos = email.find('@');
cout <<"userName= "<< email.substr(0, pos ) << endl;
}