設計模式2:建立型-建立物件
阿新 • • 發佈:2020-10-31
技術標籤:C++筆記
01 string基本概念
- 本質:string本質上是一個類
- 與char的區別:
1)char是一個指標
2)string是一個類,類的內部封裝了char*,管理這個字元 串,是char*型的容器,所以底層還是char*
- 特點:
1)string類內部封裝了很多成員方法,例如查詢find,拷貝copy,刪除delete,插入insert
2)string管理char*所分配的記憶體,不用擔心複製越界和取值越界等,由類內部負責
02 string建構函式
string();
string(cont char*s);
string(const string& str);
//四種構造方法
#include<iostream>
#include<string>
using namespace std;
void test()
{
string s1;//預設構造
char* str=" abcd ";
string s2(str);
cout<<"s2="<<s2<<endl;
string s3(s2);
cout<<"s3="<<s3<<endl;
string s4(10,'a');
cout<<"s4="<<s4<<endl;
}
int main()
{
test();
system("pause");
return 0;
}
03 string賦值操作
//六種賦值操作
#include<iostream>
#include<string>
using namespace std;
void test()
{
string s1;//預設構造
s1="helllo";
cout<<"s1=" <<s1<<endl;
string s2;
s2=s1;
cout<<"s2="<<s2<<endl;
string s3;
s3.assign("world");
cout<<"s3="<<s3<<endl;
string s4;
s4.assign("this is flower",6);
cout<<"s4="<<s4<<endl;
string s5;
s5.assign(s4);
cout<<"s5="<<s5<<endl;
string s6;
s6.assign(7,'n');
cout<<"s6="<<s6<<endl;
}
int main()
{
test();
system("pause");
return 0;
}
04 string字串拼接
在字串末尾拼接字串
#include<iostream>
#include<string>
using namespace std;
void test()
{
string s1;
s1="today is ";
s1+="Monday";
cout<<"s1="<<s1<<endl;
s1+=',';
cout<<"s1="<<s1<<endl;
string s2="time is ";
s1+=s2;
cout<<"s1="<<s1<<endl;
s1.append("13:00");
cout<<"s1="<<s1<<endl;
string s3="。。。";
s1.append(s3);
cout<<"s1="<<s1<<endl;
}
int main()
{
test();
system("pause");
return 0;
}
05 string查詢和替換
查詢:查詢指定字串是否存在
替換:在指定位置替換字串
#include<iostream>
#include<string>
using namespace std;
//查詢
void test1()
{
string s1="ComponentsUSponringArmComponent";
int pos1=s1.find("on");//如果找到,返回起始下標(預設從下標為0的位置查詢)
if(pos1==-1)
{
cout<<"not find!"<<endl;
}
else
{
cout<<"pos1="<<pos1<<endl;
}
int pos2=s1.find("on",8);//從下標為8的位置開始查詢
if(pos2==-1)
{
cout<<"not find!"<<endl;
}
else
{
cout<<"pos2="<<pos2<<endl;
}
//find是從左往右查詢,rfind是從右往左查詢
int pos3=s1.rfind("on");
if(pos3==-1)
{
cout<<"not find!"<<endl;
}
else
{
cout<<"pos3="<<pos3<<endl;
}
}
void test2()
{
string s1="mondaysunday";
//替換從下標為2的位置起 三個位置替換為 000000
s1.replace(2,3,"000000");
cout<<"s1="<<s1<<endl;
}
int main()
{
test1();
test2();
system("pause");
return 0;
}