目录
C++里的STL容器使用(二)https://blog.csdn.net/qq_38487155/article/details/89416217
一、String类
#include <iostream>
#include <string>
#include "algorithm"
using namespace std;
/*
string类的各种常见用法
s.c_str():返回元素指针
s.at():与s.size()同理,但s.at()在try里能够捕捉到异常
s.asend(10,'a'):初始化一个10个'a'字符的字符串
s.find(h,pos):从s字符串的pos下标开始查找字符串h,有则返回首个字符下标,没有则返回string::npos
s.replace(pos,n,h):从s的pos下标开始的n个字符用字符串h取代。
s[n]:下标为n的字符串
getline(cin,s):输入字符串
s.size()和s.length():返回字符串长度
s.empty():判断字符串是否为空
s.erase(pos,n):删除从pos下标开始的n个字符
s.substr(pos,n):抓取从pos下标开始的n个字符串
s.insert(pos,h):在pos下标前插入字符串h
*/
void main1()
{
//string的初始化
/*string s2("abc"); //使用构造函数
string s1="abc"; //=重载函数
string s3=s1; //复制构造函数
string s4(5,'0'); //将5个0字符复制给s4
cout<<s1<<endl<<s2<<endl<<s3<<endl<<s4<<endl;*/
//string的编历:三种方式
// 1.数组方式:s[]
// 2.at函数方式:s.at(i)
// 3.迭代器方式:string::iterator it
// 注意:s[]在try里捕捉不到异常,s.at()在try里捕捉得到异常。
/*
string s="abcde";
for(int i=0;i<s.length();i++)
{
cout<<s[i]<<"\t";
}
cout<<endl;
for(int i=0;i<s.length();i++)
{
cout<<s.at(i)<<"\t";
}
cout<<endl;
for(string::iterator it=s.begin();it<s.end();it++)
{
cout<<*it<<"\t";
}
cout<<endl;
try
{
for(int i=0;i<s.length()+3;i++)
{
cout<<s.at(i)<<"\t";
}
cout<<endl;
}
catch(...)
{
cout<<"捕捉到异常"<<endl;
}*/
//提取string里的字符指针用c_string()函数。
//提取string里的内容到字符数组用copy(s,n,pos=0),表示将string里从pos下标(默认为0)开始的n个字符复制给字符数组s
/*
string s="Hello World";
char t[50]={0};
const char *p;
p=s.c_str();
cout<<p<<endl;
s.copy(t,5,6);
cout<<t<<endl;
s.copy(t,12);
cout<<t<<endl;
*/
//string里的字符串相加:+=,+,或者append()函数
/*
string s1="abc",s2="def",s3="ghi";
s1=s1+s2;s2+=s3;
cout<<s1<<"\t\t"<<s2<<endl;
s1.append(s3);
cout<<s1<<"\t"<<s2<<endl;
*/
//string里的查找与替换
/*string s1="abc shendaye abc dibiaozuiqiang abc";
int n=s1.find("abc",0);
cout<<"abc出现下标如下所示:"<<endl;
while(n!=string::npos)
{
cout<<n<<endl;
n++;
n=s1.find("abc",n);
}*/
/*
string s1="abc shendaye abc dibiaozuiqiang abc";
int n=s1.find("abc",0),m=strlen("abc");
while(n!=string::npos)
{
s1.replace(n,m,"ABC");
n++;
n=s1.find("abc",n);
}
cout<<s1<<endl;
*/
//string里的插入与删除
/*
string s1=" World",s2="!!!",s3="Hello";
s1.insert(0,s3); //前插法:在0下标前插入字符串
s1.insert(s1.length(),s