STL学习笔记

String容器

1.at()

#include
#include
using namespace std;

int main(){
	string s="asdfgh";
	for(int i=0;i<s.size();i++){
		cout<<s.at(i)<<" ";
	}
}

STL学习笔记_第1张图片

2.拼接字符串,"+"或append()

#include
#include
using namespace std;

int main(){
	string s="asdfgh";
	s+="12345";
	cout<<s<<endl;
	string s2="ghjkl";
	s2.append(s);
	cout<<s2;
}

STL学习笔记_第2张图片

3.查找,find(),rfind()

#include
#include
using namespace std;

int main(){
	string s="abcdefg";
	int pos1=s.find("dg");
	int pos2=s.find("fg");
	cout<<pos1<<endl;
	cout<<pos2;
}

STL学习笔记_第3张图片

#include
#include
using namespace std;

int main(){
	string s="abbcaabbbbaa";
	int pos1=s.find("b");//查找第一次出现的的位置 
	int pos2=s.rfind("b");//查找第二次出现的位置 
	cout<<pos1<<"\n"<<pos2;
}

STL学习笔记_第4张图片

4.replace()替换

#include
#include
using namespace std;

int main(){
	string s="abbcaabbbbaa";
	s.replace(0,4,"11111");
	cout<<s;
}

STL学习笔记_第5张图片

5.compare()字符串的比较

compare()在>时返回1,<时返回-1,==时返回0
大写A比小写a小

#include
#include
using namespace std;

int main(){
	string a,b;
	a="asdf";
	b="asdf";
	if(a.compare(b)==0){
		cout<<"True";
	}
	else cout<<"False";
}

STL学习笔记_第6张图片

6.字串函数substr()

在这里插入图片描述

#include
#include
using namespace std;

int main(){
	string a,b;
	a="abc12345";
	b=a.substr(2,4);
	cout<<b;
}

STL学习笔记_第7张图片

7.插入和删除

insert(int pos,string& str)插入字符串
insert(int pos,int n,char c)在指定位置插入n个字符
erase(int pos,int n)删除从pos开始的n个字符

#include
#include
using namespace std;

int main(){
	string a;
	a="abc12345";
	a.insert(2,"###");
	cout<<a<<endl;
	a.insert(2,10,'*');
	cout<<a<<endl;
	a.erase(2,5);
	cout<<a<<endl;
}

在这里插入图片描述

你可能感兴趣的:(STL学习,学习,c++,visual,studio)