使用string需添加的头文件
//添加头文件
#include<string>
using namespace std;
string类型初始化的几种方式
//**初始化的几种方式**//
//有括号无等于号,有等于号无括号
//直接赋字符串————直接初始化
string s3 = "Liubing";
cout << "s3= " << s3<<endl;
//用括号直接赋字符串————拷贝初始化
string s1("Hello");
cout <<"s1= "<< s1 << endl;
//使用其他字符串初始化
string s2=s1;
//等价于:
string s2(s1);
//使用单个字符初始化
string s2(8, '*'); //8个连续的*
cout << "s2= "<<s2 << endl;
string中内容的访问
(1)通过数组下标访问
cout << "1、通过数组方式遍历:" <<endl;
for (int i = 0; i < s1.length(); i++){
cout << s1[i] << " ";
}
cout << endl;
(2)通过迭代器访问
cout << "2、通过迭代器遍历:" <<endl;
//for循环括号内也可写为:
//for(auto it=s1.begin();it!=s1.end();it++)
for(string::iterator it = s1.begin(); it!= s1.end(); it++){
cout << *it << " ";
}
cout << endl;
(3)通过at()函数访问
str.at()用于获取指定字符;at(i),i就是想要获取的字符的下标,函数返回值为指定的字符
str.at(i)与str[i]的含义一样,返回arr中第i个元素,唯一的区别在于at()函数比[]运算符更安全,因为at()不会去访问越界的元素
//通过at()方式遍历
cout << "3、通过at()方式遍历:" <<endl;
for (int i = 0; i < s1.length(); i++){
cout << s1.at(i) << " "; //此方式可以在越界时抛出异常
}
cout << endl;
}
string中字符串拼接
(1)直接相加拼接
cout << "字符串连接:" <<endl;
cout << "方式1:" <<endl;
string s1 = "123";
string s2 = "456";
s1 += s2;
cout << "s1 = "<< s1 << endl;
//输出结果:
字符串连接:
方式1:
s1 = 123456
(2)使用append()函数拼接
cout << "字符串连接:" <<endl;
cout << "方式2:" <<endl;
string s3 = "123";
string s4 = "456";
s3.append(s4);
cout << "s3 = "<< s3 << endl;
//输出结果:
字符串连接:
方式2:
s3 = 123456
string中插入字符串/str.insert()
(1)insert(pos,s),在pos号位置插入字符串s
string str="abcxyz",str2="opq";
//在str[3]处插入opq,在str2位置直接写"opq"也可以
str.insert(3,str2);
cout<<str<<endl;
//输出结果:
//abcopqxyz
(2)insert(it,it2,it3),it为原字符串欲插入位置,it2,it3为待插入字符串的首尾迭代器,用来表示串[it2,it3)将被插入在it的位置上
string str="abcxyz",str2="opq";
//在str[3]处插入str2:
str.insert(str.begin()+3,str2.begin(),str2.end());
cout<<str<<endl;
//输出结果:
//abcopqxyz
返回string中的子串str.substr()
substr(pos,len):返回从pos号位开始,长度为len的子串,时间复杂度O(len)
string str="Thank you for your smile.";
cout<<str.substr(0,5)<<endl;
cout<<str.substr(14,4)<<endl;
cout<<str.substr(19,5)<<endl;
//输出结果:
//Thank
//your
//smile
(3)push_back() 追加字符到字符串
(4) pop_back() 删除最后一个字符
operator+= 添加到字符串(公共成员函数)
append 追加到字符串(公共成员函数)
assign 给字符串赋值(公共成员函数)
insert 插入字符串(公共成员函数)
erase 从字符串中删除字符(公共成员函数)
replace 替换字符串的一部分(公共成员函数)
swap 交换字符串值(公共成员函数)
添加(append、push_back、+=); append 可以在字符串的末尾添加字符和字符串, push_back 只适用于添加单个字符
string类型和其他数据类型相互转换的函数
(1) string类型转换int,long,double:atoi(),atol(),atof()
string类型转换为int类型:atoi()函数,常常需要和 c_str()函数连用
atoi的参数类型为(const char *nptr)
而string是一个类,所以需要获取str的首地址即str.c_str()
string str="123";
int num=atoi(str.c_str());
类似的函数:
long lnum=atol(str.c_str());把字符串转换成长整型数
double dnum=atof(str.c_str());把字符串转换成浮点数
(2) C++string转换为C的字符串数组:c_str()
(3) int类型转换为string类型:to_string()
int num=123;
string str=to_string(num);