#include<iostream>
#include<string>
using namespace std;
//string的构造函数
//string();
//string(const char* s);
//string(const string& str);
//string(int n, char c);
void test01()
{
string s1;//默认构造
const char * str = "hello world";
string s2(str);
cout << "s2=" << s2 << endl;
string s3(s2);
cout << "s3=" << s3 << endl;
string s4(10, 'a');//十个a
cout << "s4=" << s4 << endl;
}
void test02()
{
string str1;
str1 = "hello world";
cout << "str1=" << str1 << endl;
string str2;
str2 = str1;
cout << "st2r=" << 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);//把前五个字符赋给str5
cout << "str5=" << str5 << endl;
string str6;
str6.assign(str5);
cout << "str6=" << str6<< endl;
string str7;
str7.assign(10, 'w');
cout << "str7=" << str7 << endl;
}
void test03()//string 字符串拼接
{
string str1 = "我";
str1 += "爱";
cout << "str1=" << str1 << endl;
str1 += "你";
cout << "str1=" << str1 << endl;
string str2 = "啊";
str1 += str2;
cout << "str1=" << str1 << endl;
string str3 = "I";
str3.append(" love ");
cout << "str3=" << str3 << endl;
str3.append("you. "啦啦啦", 4);
cout << "str3=" << str3 << endl;
string str4;
str4.append(str3, 0, 11);//参数2从哪个位置开始(第一个是0位置),参数3是截取字符个数
cout << "str4=" << str4 << endl;
}
void test04()//查找和替换
{
string str1 = "abcdefg";
int pos = str1.find("de");//position
cout << "pos=" << pos << endl;//输出3,d在第三个位置
pos = str1.find("df");//position
cout << "pos=" << pos << endl;//因为没有,所以输出-1
if (pos == -1)
{
cout << "未找到字符串" << endl;
}
else
{
cout << "找到字符串,pos=" << pos << endl;
}
//rfind和find区别:rfind从右往左找,find从左往右找
pos = str1.rfind("de");//输出3
}
void test05()
{
string str1 = "abcdefg";
str1.replace(1, 3, "11111");//从1号位置起三个字符替换为1111 输出a1111efg
cout << str1 << endl;
}
void test06()
{
string str1 = "hello";
string str2 = "hello";
if (str1.compare(str2) == 0)
{
cout << "等于";//>0,<0
}
}
void test07()//字符存取
{
string str = "hello";
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';
cout << str << endl;
str.at(1) = 'x';
cout << str << endl;
}
void test08()//插入和删除
{
string str = "hello";
str.insert(1, "111");//h111ello
cout << str << endl;
//删除
str.erase(1, 3);
cout << str << endl;//hello
}
void test09()//string 求子串
{
string str = "abcdef";
string substr = str.substr(1, 3);//从位置1开始截三个
cout << substr << endl;
}
void test10()
{
string email = "lzb@qq.com";
int pos = email.find("@");
string usrname = email.substr(0, pos );
cout << usrname << endl;
}
int main()
{
test10();
}
string容器
最新推荐文章于 2023-11-22 15:54:28 发布