1.
string的构造函数:
void test()
{
//1.
string s1;//默认构造
//2.
const char *str = "hello world";
string s2(str);
cout<< s2 <<endl;
//3.
string s3(s2);//拷贝构造
//4.
string(10,'a');//十个a
}
2.string的赋值操作( 函数str.assgin() )
示例:六种
void test()
{
string str1;
str1 = "Hello World";
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(10, 'w');
cout << "str6 =" << str6 << endl;
}
输出结果:
3. string字符串拼接 (函数:str.append())
void test()
{
string str1 = "我";
str1 += "爱玩游戏";
cout << "str1 =" << str1 << endl;
string str2 = "LOL DNF";
str1 += str2;
cout << "str1 =" << str1 << endl;
string str3 = "I";
str3.append("love");
str3.append("game abcd", 4);
cout << "str3 =" << str3 << endl;
string str4 = "I";
str4.append("love");
str4.append(str2, 4, 3);//第四个字符开始,截取三个字符
cout << "str4 =" << str4 << endl;
}
输出结果:
4. 字符串的比较(函数:str.compare(str1) )
代码:
void test()
{
string str1 = "hello";
string str2 = "xello";
if (str1.compare(str2) == 0)
{
cout << "相等" << endl;
}
else if (str1.compare(str2) > 0)
{
cout << "str1大于str2" << endl;
}
else
{
cout << "str2小于str1" << endl;
}
}
运行结果:
5. 字符的存取(函数:str[] , str.size() 和 str.at() )
void test()
{
string str1 = "Hello world";
//两种方法打印逐个字符串
//[]
for (int i = 0; i < str1.size(); i++)
{
cout << str1[i] << " ";
}
cout << endl;
//str.at()
for (int j = 0; j < str1.size(); j++)
{
cout << str1.at(j) << " ";
}
cout << endl;
//字符串修改
str1 [0] = 'x';
str1.at(1) = 'p';
cout << str1 << endl;
}
输出结果:
6. 子串获取(函数:substr)
void test()
{
string str1 = "abcdefg";
//截取从1~3的字符
string Substr = str1.substr(1, 3);
cout << "Substr =" << Substr << endl;
//尝试查找邮箱的用户名:
string email = "1604900106@qq.com";//创建一个邮箱
int pos = email.find("@");//找到‘@’的位置
string username = email.substr(0, pos);//截取username的字符串
cout << "username = " << username << endl;
}
输出结果: