STL --string容器

1概念

1.優點

  • string封裝了char* 管理這個字符串,是一個char* 型的容器
  • string 封裝了很多實用的方法 find copy delete
  • string 不用考慮內存越界和釋放

2常用的API

2.1初始化

#include<iostream>
#include<cstring>

void tset(){
	string s1;
	string s2("dadadad");
	string s3(10,'a');
	string s4(s3);
}

2.2賦值操作

void tset3(){
	string s1;
	string s2("appppp");
	s1="adsadsad";
	s1=s2;
	s1='a';

2.3[] /at

  • []方式,如果訪問越界 直接掛了
  • at方式 訪問越界 拋異常out_of_range
void test8(){
	string s1="wasdadadaf";
	for(int i=0;i<s1.size();i++){
		cout<<s1[i]<<" ";
	}
	
	for(int i=0;i<s1.size();i++){
		cout<<s1.at(i)<<" ";
	}
}

2.4拼接操作

  • 重載+=操作符
    在這裏插入圖片描述
}
void tset()4{
	string s="abjdsfd";
	string s2="asdasda";
	
	s+="ADSASDAFS";
	s+=s2;
	
	string s3="2222";
	//將s3加在s2後面
	s2.append(s3);

	string s4 =s2+s3;
}

2.5查找和替換操作

在這裏插入圖片描述

void tset6(){
	string s="abcdasd";
	零個位置開始 替換2個位置字符
	s.replace(0,2,"1111");//結果:1111abcdasd

}

2.6子串

在這裏插入圖片描述

2.7插入和刪除

在這裏插入圖片描述

2.8string和char* 轉換

在這裏插入圖片描述

2.9 比較

void string7(){
	string s1="abcdef";
	string s2="abcasd"
	if(s1.compare(s2)==0){
		cout<<"相等"<<endl;
	}else{
		cout<<"不相等"<<endl;
	}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章