C++中表示字符串不仅可以用C语言的字符数组,还可以使用string,string是一种储存字符的数据结构类,内置了很多操作函数,用起来十分方便,可以完全替代字符数组。对string用法进行简单记录。
string的创建方式有很多种,常用的创建方式有
#include
#include
using namespace std;
int main() {
string p1; //默认为""
string p2 = "cccccc";
string p3("123");
}
掌握几种基本的就够用了。
string可以通过下标访问其每一个字符,这一点与字符数组一致。
string类重载了<<操作符,可以直接用cout显示
#include <string.h>
#include <iostream>
using namespace std;
int main() {
string p1 = "good good study.";
cout<<p1<<endl;
char a = p1[1];
cout<<a<<endl;
}

使用insert函数,函数原型为:
string& insert (size_t pos, const string& str);
pos:插入位置
str:要插入的字符,既可以是string,也可以是char数组
示例:
#include <string.h>
#include <iostream>
using namespace std;
int main() {
string p1 = "good good study.";
cout<<p1<<endl;
p1.insert(1,"111");
cout<<p1<<endl;
}

string删除字符可以使用erase函数,函数原型为:
string& erase (size_t pos = 0, size_t len = npos);
pos:开始位置
npos:长度,如果超过了string 的长度,则会删除pos后边的所有字符
示例:
#include
#include
using namespace std;
int main() {
string p1 = "good good study.";
cout<<p1<<endl;
p1.erase(2,5);
cout<<p1<<endl;
p1.erase(5,50);
cout<<p1<<endl;
}

string字符串查找可以使用find函数,原型为:
size_t find (const string& str, size_t pos = 0) const;
str:待查找的字符串,可以是string,也可以是char[]
pos:从哪开始查找,默认为从头开始
返回值:第一次找到的索引
示例:
#include
#include
using namespace std;
int main() {
string p1 = "good good study.";
int a = p1.find("good");
cout<<a<<endl;
a = p1.find("good",1);
cout<<a<<endl;
}

拼接可以使用加号”+“或者append函数。
”+“ 不仅支持string之间运算,也支持string与char[]拼接。
示例:
#include
#include
using namespace std;
int main() {
string p1 = "bood";
string p2 = "good";
string p3 = p1 + p2 + "study";
cout<< p3 <<endl;
}

当然,也可以用append函数实现,不过感觉还是“+”更方便。、
使用substr函数提取字字符串,函数原型为:
string substr (size_t pos = 0, size_t len = npos) const;
pos:开始位置
npos:提取长度
示例:
#include
#include
using namespace std;
int main() {
string p1 = "good good study.";
cout<< p1 <<endl;
string p2 = p1.substr(5,4);
cout<< p2 <<endl;
}

string的字符串替换可以使用replace函数,原型为:
string replace(size_t pos, size_t len, const string& str)
示例:
#include
#include
using namespace std;
int main() {
string p1 = "good good study.";
cout<< p1 <<endl;
p1.replace(1,3,"aaa");
cout<< p1 <<endl;
}

除了上边函数,string还有很多好用的函数:
length:返回string长度。用法:string.length()
c_str:返回C语言的字符数组,多用于函数传参的时候,因为很多函数只接收C类型字符数组。用法:string.c_str()
swap:交换两个string的内容。用法:swap(p1, p2)
empty:判断string是否为空。用法:string.empty()