目录
1、将一个 string 对象赋值给另一个 string 对象
6、string.pop_back()删除字符串最后一个元素
string的概念:
string是C++标准库的一个重要的部分,主要用于字符串处理。
相关头文件 :
#include <string>
string的定义:
string str; //str为空字符串,长度为 0(默认构造函数)
常用函数:
length():得到字符串长度
C语言中使用strlen()来获取字符串长度
C++中使用
str.size()
或str.length()
.
string str("hello!");
int len1 = str.size();
int len2 = str.length();
empty():判断是否为空
if(str.empty())
return;
substr():截取字符串
string substr(pos,npos) ;//返回pos开始的n个字符组成的字符串
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s = "hello, world!";
string ss1 = s.substr(2); //llo, world!
string ss2 = s.substr(2,3); //llo
cout << ss1 << endl << ss2 << endl;
return 0;
}
find():查找字符或字符串
1、s.find(str,position)
①str:是要找的元素
②position:字符串中的某个位置,表示从从这个位置开始的字符串中找指定元素。
4、返回值为目标字符的位置,当没有找到目标字符时返回-1
#include<bits/stdc++.h>
using namespace std;
int main(){
string s="abcdefg";
cout << s.find('e') << endl;//4
cout << s.find("bcd") << endl;//1
cout << s.find('e',4) << endl;//4,从下标为4开始搜索,输出-1;
return 0;
}
rfind():反向查找
1、与 string.find() 方法类似,只是查找顺序不一样
2、string.rfind() 是从指定位置 pos (默认为字符串末尾)开始向前查找,直到字符串的首部,并返回第一次查找到匹配项时匹配项首字符的索引。
3、换句话说,就是查找子字符串或字符最后一次出现的位置
replace():替代
用str替换指定字符串从起始位置pos开始长度为len的字符
#include<bits/stdc++.h>
using namespace std;
int main(){
string str = "abcdefghigk";
str=str.replace(3,2,"#*"); //第三个位置开始的字符替换成#*
cout<<str<<endl;
return 0;
}
insert():插入字符
#include<bits/stdc++.h>
using namespace std;
int main(){
string s=",";
s.insert(0,"heo");
cout<<s<<endl;//heo,——在索引为2的位置插入heo
s.insert(4,"world",2);
cout<<s<<endl;//heo,wo——在索引为4的位置插入world的前2个字符
s.insert(2,2,'l');
cout<<s<<endl;//插入l2次
s.insert(s.end(),'r');
cout<<s<<endl;//使用迭代器,在s末尾插入r
s += "ld!";
cout<<s<<endl;//在开头或者末尾插入可以用运算符
return 0;
}
append():追加字符
#include<bits/stdc++.h>
using namespace std;
int main(){
string str("hello");
string str2(",world!");
str.append(str2);
cout<<str<<endl; //hello,world!
return 0;
}
swap():交换字符串
#include<bits/stdc++.h>
using namespace std;
int main(){
string str1 = "hello";
string str2 = "HELLO";
str1.swap(str2);
cout<<str1;
return 0;
}
一些小用法:
1、将一个 string 对象赋值给另一个 string 对象
string str("hello!");
string str2;
str2 = str;
2、string 对象的拼接
string str1("hello");
string str2("world");
string str3 = str1 + str2;
3、对于string对象的比较,可以直接使用关系运算符
string str1("abcd");
string str2("abcd");
if(str1 == str2)