- 字符串的拼接
- 查找和替换
- 比较
- 获取
- 插入和删除
- 字符串的子串 拿来截取一段字符串中的一段
#include<iostream>
#include<vector>
#include<string>
using namespace std;
void test01()
{
string s1;
const char* str = "hello world";
string s2(str);
cout << "str = " << s2 << endl;
string s3(s2);
cout << "str = " << s3 << endl;
string s4(10, 'a');
cout << "str = " << s4 << endl;
}
void test02() {
string s1;
s1 = "hello world";
cout << "s1 = " << s1 << endl;
string s2;
s2 = s1;
cout << "s2 = " << s2 << endl;
string s3;
s3.assign("hello c++");
cout << "s3 = " << s3 << endl;
string s4;
s4.assign("hello c++",5);
cout << "s4 = " << s4 << endl;
string s5;
s5.assign(s4);
cout << "s5 = " << s5 << endl;
string s6;
s6.assign(5, 'x');
cout << "str6 = " << s6 << endl;
}
void test03() {
string s1 = "我";
s1 += " ai xiaobai";
cout << s1 << endl;
s1 += ':';
cout << s1 << endl;
string s2="打王者荣耀";
s1 += s2;
cout << s1 << endl;
string s3="我爱玩";
s3.append("你爱玩吗");
cout << s3 << endl;
s3.append("如果你爱玩可以一起玩", 10);
cout << s3 << endl;
s3.append("如果你爱玩可以一起玩", 10, 10);
cout << s3 << endl;
}
void test04()
{
string str1 = "abcdefgh";
int pos = str1.find("de");
if (pos == -1)
{
cout << "bu存在" << endl;
}
else
{
cout << "存在" << endl;
}
pos = str1.rfind("de");
cout << "pos = " << pos << endl;
string str2 = "abcdefg";
str2.replace(1, 3, "111");
cout << str2 << endl;
}
void test05()
{
string s1 = "我是小白的主ren";
string s2 = "我是小白的主rn";
int ret = s1.compare(s2);
if (ret == 0)
{
cout << "s1 = s2" << endl;
}
else if (ret == 1)
{
cout << "s1 > s2" << endl;
}
else
{
cout << "s1 < s2" << endl;
}
}
void test06()
{
string s1 = "abcd4";
for (int i = 0; i < s1.size(); i++)
{
cout << s1[i] << " " ;
}
cout << endl;
for (int i = 0; i < s1.size(); i++)
{
cout << s1.at(i) << " ";
}
cout << endl;
s1[0] = 'z';
s1.at(1)='h';
cout << s1 << endl;
}
void test07()
{
string s1 = "hello ";
s1.insert(1, " world");
cout << s1;
s1.erase(1, 3);
cout << s1 << endl;
}
void test08()
{
string str1 = "abcdef";
string substr = str1.substr(1, 3);
cout << "substr = " << substr << endl;
string email = "993667249@qq.com";
int pos = email.find("@");
string username = email.substr(0, pos);
cout << "username: " << username << endl;
}
int main()
{
test01();
cout << "-----------" << endl;
test02();
test03();
test04();
test05();
test06();
test07();
test08();
return 0;
}