目录
构造函数
赋值操作
字符串拼接
查找替换
字符串比较
字符串存取
插入删除
字符串截取
构造函数
#include<iostream>
using namespace std;
#include<string>
//string 的构造函数
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');
cout << s4;
}
赋值操作
// 赋值操作
void test02()
{
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(str5);
cout << "str6=" << str6 << endl;
string str7;
str7.assign(10, 'w');
cout << "str7=" << str7 << endl;
}
字符串拼接
//字符串拼接
void test03()
{
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 ");
cout << "str3=" << str3 << endl;
str3.append("game ,abcd", 4);
cout << "str3=" << str3 << endl;
str3.append(str2,3);
cout << "str3=" << str3 << endl;
}
查找替换
//字符串查找和替换
//1.查找
void test04()
{
string str1 = "abcdefg";
int pos =str1.find("df");
if (pos == -1)
{
cout << "未找到字符串" << endl;
}
else
{
cout << "找到字符串,pos=" << pos << endl;
}
cout << "pos=" << pos << endl;
// rfind 从右往左查找
//find 从左往右查找
}
// 替换
void test044()
{
string str1 = "abcdefg";
str1.replace(1, 3, "1111");
cout << "str1=" << str1 << endl;
}
字符串比较
//字符串比较
void test05()
{
string str1 = "hello";
string str2 = "hello";
if (pare(str2) == 0)
{
cout << "str1 = str2" << endl;
}
else if (pare(str2) > 0)
{
cout << "str1>str2" << endl;
}
else
{
cout << "str1<str2" <<endl;
}
}
字符串存取
//string字符存取
void test06()
{
string str = "hello";
cout << str << endl;
//1.通过[]访问单个字符
for (int i = 0; i < str.size(); i++)
{
cout << str[i] << " ";
}
//2.通过at方式访问单个字符
for (int i = 0; i < str.size(); i++)
{
cout << str.at(i) << " ";
}
cout << endl;
//修改单个字符
str[0] = 'x';
cout << str;
str.at(1) = 'x';
cout << str;
}
插入删除
//字符串的插入和删除
void test07()
{
string str = "hello";
//插入
str.insert(1, "111");
cout << "str=" << str << endl;
//删除
str.erase(1, 3);
cout << "str=" << str << endl;
}
字符串截取
//字符串的截取
void test08()
{
string str = "abcdef";
string substr = str.substr(1, 3);//从 1 位置起,截取三个字符
cout << "substr =" << substr << endl;
}
void test088()
{
string email = "zhangsan@";
int pos = email.find("@");
string usename = email.substr(0, pos);
cout << usename;
}