字符串常用功能

字符串初始化操作

常见操作

string s1; // s1 = ""
string s2 = string(); // s2 = ""
string s3 = "Hello"; // 拷贝初始化为"hello"

构造初始化

string s1("World"); // 直接初始化
string s2(5, 'A'); // "AAAAA"
string s3(10, '*');  // "**********"         

列表初始化

string s1{'R'}; // "R"
string s2{'a','b','c','\0'}; // "abc"
string s3{"C++"}; // "C++"

字符串访问操作

下标访问 []

string s = "hello";
char c = s[1]; // 'e'
char c2 = s[10]; // 越界不抛异常,但有风险崩溃

安全访问 at()

string s = "hello";
char c = s.at(1); // 'e'
char c2 = s.at(10); // 抛异常

首尾访问 front() back()

string s = "hello";
char c = s.front(); // 'h'
char c2 = s.back(); // 'o'

迭代器访问 begin() end()

string s = "hello";
auto it1 = s.begin();
cout<<*it1; // 'h'

容量 empty() size() length()

string s = "hello";
bool f = s.empty(); // 空true 非空false
int a = s.size(); // 5 大小
int b = s.length(); // 5 长度,与size作用相同

字符串数据操作

字符串清空 clear()

string s = "hello";
s.clear();
cout<<s.size(); // 0,字符串中什么都没有了,大小为0

字符串更改大小 resize()

string s = "hello";
s.resize(3); // "hel" 截断
s.resize(8); // "hel"+5个'\0'
cout<<s.size(); // 8
s.resize(10,'k'); // "helkkkkkkk" 空字符填充'k'

字符串插入 insert()

string s = "hello";
s.insert(2,"xyz"); // "hexyzllo" 2下标位置插入xyz

字符串增加、删除末尾字符 push_back() pop_back()

string s = "hello";
s.push_back('A'); // "helloA"

string s = "hello";
s.pop_back(); // "hell"

字符串追加多个内容 append() +=

string s = "hello";
s.append("world"); // "helloworld"
s.append(5,"!"); // "helloworld!!!!!"

s+="~~~"; // "helloworld!!!!!~~~"

字符串删除字符 erase()

string s = "helloworld";
s.erase(5,3); // "hellold"从5下标删除3个字符

字符串替换字符 replace()

string s = "hello world";
s.replace(6,5,"C++"); // "hello C++"从6下标开始的5个字符替换成C++

字符串提取字串 substr()

string s = "hello world";
string str1 = s.substr(7); // "orld" 从下标7开始到最后
string str2 = s.substr(4,3); // "o w" 从下标4开始的3个字符

字符串倒序 reverse() 非字符串独有用法

string s = "12345";
reverse(s.begin(),s.end());
cout<<s; // "54321"

字符串比较 compare()

非复杂要求的情况下建议直接使用关系运算符

字符串的类型转换

字符串转数值

string s1 = "123";
int a = stoi(s1); // 将s1转换成数字123并赋值给a

string s2 = "12345678912345";
long long b = stoll(s2); // 将s2转换成数字12345678912345并赋值给b

string s3 = "123.456";
float c = stof(s3); // 将s3转换成数字123.456并赋值给c

string s4 = "-123.456";
double d = stod(s4); // 将s4转换成数字-123.456并赋值给d

高级用法自行了解(锁定标记、自动转进制)

数值转字符串

int num = 12345;
string s1 = to_string(num); // 将整数转换成"12345"并赋值给s1

double pi = 3.14;
string s2 = to_string(pi); // 将浮点数转换成"3.140000"并赋值给s2(默认精度6位)

字符串转字符数组

string s = "hello";
const char* c = s.c_str();

补充:字符串查询find()

如果存在,则返回下标位置,不存在,则返回unsigned long long的最大值,如果结果赋值给int类型,则是-1

string s = "hello";
int a = s.find("ll"); // 查询字符串s中是否包含子串"ll"
int b = s.find('e'); // 查询字符串s中是否包含字符'e'