十六.STL 之 string 容器
代码片内有详解
:
1.Code
:
#include<iostream>
using namespace std;
#include<string>
void test()
{
string s1;
cout << "str1 = " << s1 << endl;
const char* str = "Hello World";
string s2(str);
cout << "str2 = " << s2 << endl;
string s3(s2);
cout << "str3 = " << s3 << endl;
string s4(10, 'a');
cout << "str3 = " << s3 << endl;
}
void test2()
{
string str1;
str1 = "Hello WoWo";
cout << "str1 = " << str1 << endl;
string str2;
str2 = str1;
cout << "str2 = " << str2 << endl;
string str3;
str3 = 'a';
cout << "str3 = " << str3 << endl;
string str4;
str4.assign("hello c++");
cout << "str4 = " << str4 << endl;
string str5;
str5.assign("hello c++", 5);
cout << "str5 = " << str5 << endl;
string str6;
str6.assign(str5);
cout << "str6 = " << str6 << endl;
string str7;
str7.assign(5, 'x');
cout << "str7 = " << str7 << endl;
}
void test3()
{
string str1 = "我";
str1 += "爱玩游戏";
cout << "str1 = " << str1 << endl;
str1 += ':';
cout << "str1 = " << str1 << endl;
string str2 = "LOL DNF";
str1 += str2;
cout << "str1 = " << str1 << endl;
string str3 = "I";
str3.append(" love ");
str3.append("game abcde", 4);
str3.append(str2, 4, 3);
cout << "str3 = " << str3 << endl;
}
void test4()
{
string str1 = "abcdefg";
int pos = str1.find("g");
if (pos == -1) { cout << "未找到" << endl; }
else cout << "pos = " << pos << endl;
pos = str1.rfind("g");
if (pos == -1) { cout << "未找到" << endl; }
else cout << "pos = " << pos << endl;
str1.replace(4, 1, "o");
cout << "str1.replace(4,1,o); str1 = " << str1 << endl;
}
void test5()
{
string s1 = "hello";
string s2 = "aello";
int ret = s1.compare(s2);
if (ret == 0)
{
cout << "s1 等于 s2" << endl;
}
else if (ret > 0)
{
cout << "s1 大于 s2" << endl;
}
else
{
cout << "s1 小于 s2" << endl;
}
}
void test6()
{
string str = "hello world";
for (int i = 0; i < str.size(); i++)
{
cout << str[i] << " ";
}
cout << endl;
for (int i = 0; i < str.size(); i++)
{
cout << str.at(i) << " ";
}
cout << endl;
str[0] = 'x';
str.at(1) = 'x';
cout << str << endl;
}
void test7()
{
string str = "hello";
str.insert(1, "111");
cout << str << endl;
str.erase(1, 3);
cout << str << endl;
string email = "hello@sina.com";
int pos = email.find("s");
string username = email.substr(pos, email.size());
cout << "username: " << username << endl;
}
int main()
{
test();
test2();
test3();
test4();
test5();
test6();
test7();
system("pause");
return 0;
}
2.The result of the run
:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/5c388b60d34038a5099c8e9839e9c99b.png#pic_center)