1.string的构造函数
#include <iostream>
using namespace std;
//string的构造函数
//string(); string(const char*s);
//string(const char& str); string(int n,char c);
void test01()
{
string s1;//默认构造
const char* str = "hello world";
string s2(str);
cout << s2 << endl;
string s3(s2);//拷贝构造
cout << s3 << endl;
string s4(10, 'a');
cout << s4 << endl;
}
int main()
{
test01();
}
2.string赋值操作
#include <iostream>
using namespace std;
//string的赋值操作
/*
string& operator=(const char* s);
string& operator=(const string &s);
string& operator=(char c);
string& assign(const char* s);
string& assign(const char* s,int n);
string& assign(const string &s);
string& assign(int n,char c);
*/
void test01()
{
string str1;
str1= "hello world";;
cout << str1 << endl;
string str2;
str2= str1;
cout << str2 << endl;
string str3;
str3 = 'a';
cout << str3 << endl;
string str4;
str4.assign("hello");
cout << str4 << endl;
string str5;//前n个字符
str5.assign("hello",1);
cout << str5 << endl;
string str6;
str6.assign(str5);
cout << str6 << endl;
string str7;
str7.assign(5,'a');
cout << str7 << endl;
}
int main()
{
test01();
}
3.string字符串拼接
#include <iostream>
using namespace std;
//string的拼接操作
void test01()
{
string str1 = "我";
str1 += "爱玩游戏";
str1 += ':';
cout << str1 << endl;
string str2 = "王者荣耀";
str1 += str2;
cout << str1 << endl;
string str3 = "I";
str3.append("love ");
str3.append("王者荣耀", 2);
cout << str3 << endl;
str3.append(str2);
cout << str3 << endl;
str3.append(str2,2,7);
cout << str3 << endl;
}
int main()
{
test01();
}
4.string查找和替换
#include <iostream>
using namespace std;
//string的查找替换操作
void test01()
{
string str1 = "abcdefgde";
int pos = str1.find("de");//从左往右查 从0开始
int re= str1.rfind("de");//从左往右查
cout << pos << endl;
cout << re<< endl;
}
void test02()
{
string str1 = "abcdef";
str1.replace(1, 3, "1111");//bcd替换成1111
cout << str1 << endl;
}
int main()
{
test01();
test02();
}
5.string 的字符串比较
#include <iostream>
using namespace std;
//string的字符串比较操作
//比较方式:字符的ASCII码
/*
=返回0
>返回1
<返回-1
*/
void test01()
{
string str1 = "hallo";
string str2 = "hello";
int flag = str1.compare(str2);
cout << flag << endl;
}
int main()
{
test01();
}
6.string 字符存取
#include <iostream>
using namespace std;
//string的字符存取
void test01()
{
string str1 = "hello";
//通过[]访问单个字符
for (int i = 0; i < str1.size(); i++)
{
cout << str1[i] << " ";
}
cout << endl;
//通过at方式访问单个字符
for (int i = 0; i < str1.size(); i++)
{
cout << str1.at(i) << " ";
}
cout << endl;
str1[0] = 'a';
str1.at(3) = 'b';
cout << str1;
}
int main()
{
test01();
}
7.string字符串插入和删除
#include <iostream>
using namespace std;
//string的字符串插入和删除
void test01()
{
string str1 = "hello";
str1.insert(1, "111");//插入后为h111ello
cout << str1 << endl;
str1.erase(1, 3);//删除插入的111
cout << str1 << endl;
}
int main()
{
test01();
}
8.string字串获取
#include <iostream>
using namespace std;
//string子串获取
void test01()
{
string str = "abcdef";
string sustr = str.substr(0, 3);//从第0个获取三个字符
cout << sustr << endl;;
}
int main()
{
test01();
}