#include <iostream>
#include <string>
using namespace std;
void test01()
{
string s1; //调用无参构造函数
cout << "s1 = " << s1 << endl;
const char *s = "hi!";
string s2(s);
cout << "s2 = " << s2 << endl;
string s3(s2); //调用拷贝构造函数
cout << "s3 = " << s3 << endl;
string s4(3, 's');
cout << "s4 = " << s4 << endl;
}
void test02()
{
string s1, s2, s3, s4, s5, s6, s7;
s1 = "hello!";
cout << "s1 = " << s1 << endl;
s2 = s1;
cout << "s2 = " << s2 << endl;
s3 = 'a';
cout << "s3 = " << s3 << endl;
s4.assign("HELLO!");
cout << "s4 = " << s4 << endl;
s5.assign("HELLO TOM!", 5);
cout << "s5 = " << s5 << endl;
s6.assign(s1);
cout << "s6 = " << s6 << endl;
s7.assign(3, 's');
cout << "s7 = " << s7 << endl;
}
void test03()
{
string s1("abcdefgde");
int pos = s1.find("de");
if (pos == -1)
{
cout << "未找到de" << endl;
}
else
{
cout << "de的第一个位置在 " << pos << endl;
}
pos = s1.rfind("de");
if (pos == -1)
{
cout << "未找到de" << endl;
}
else
{
cout << "de的最后一个位置在 " << pos << endl;
}
s1.replace(pos, 2, "TTTTT");
cout << "s1 = " << s1 << endl;
}
void test04()
{
string s1("abcd");
string s2("badd");
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 test05()
{
string s1("abcdefg");
for (int i = 0; i < s1.size(); ++i)
{
cout << s1[i] << " ";
}
cout << endl;
for (int i = s1.size() - 1; i >= 0; --i)
{
cout << s1.at(i) << " ";
}
cout << endl;
s1[3] = 'T';
s1.at(5) = 'T';
cout << "s1 = " << s1 << endl;
}
void test06()
{
string s1("abcdefg");
s1.insert(0, "hello ");
cout << "s1 = " << s1 << endl;
s1.erase(0, 2);
cout << "s1 = " << s1 << endl;
}
void test07()
{
string email("tom@foxmail.com");
int pos = email.find('@');
if (pos != -1)
{
string name = email.substr(0, pos);
string mail_company = email.substr(pos + 1, email.size() - pos + 1);
cout << "name : " << name << ", email company : " << mail_company << endl;
}
}
int main(int argc, char const *argv[])
{
/*1. string是一个类,类内部封装了char*,管理这个字符串,是一个char*型的容器
2. string管理char*所分配的内存,不用担心复制越界和取值越界等,由类内部进行负责
*/
//string构造函数
test01();
//string赋值操作
test02();
//查找和替换
test03();
//字符串比较
test04();
//字符存取
test05();
//插入和删除
test06();
//子串
test07();
return 0;
}
STL-string
最新推荐文章于 2024-07-18 23:31:00 发布