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