最近学习STL,想借此机会学习总结一下。
String类包含在中,要使用时候要包含进来。
1.String初始化
#include <iostream>
#include <string>
using namespace std;
void String_Init()
{
string s1 = "Kevin";
string s2("Tom");
string s3 = s2;
string s4(10,'a'); //初始化10个a
}
2.String遍历
#include <iostream>
#include <string>
using namespace std;
void String_Iteror()
{
string s1 = "aaabbbccc";
for(int i = 0;i < s1.length();i++)
{
cout<<s1[i]<<endl;
}
for(string::iterator it = s1.begin();it != s1.end();it++)
{
cout<<*it<<endl;
}
}
这里注意求长度有两个,一个是size,一个是length。结果是一样的。
3.String连接
#include <iostream>
#include <string>
using namespace std;
void String_Connect()
{
string s1 = "aabb";
string s2 = "vvv";
cout<<s1+s2<<endl;
string s3 = "qwert";
s3.append(s2);
cout<<s3<<endl;
}
4.字符串查找
#include <iostream>
#include <string>
using namespace std;
void String_Find()
{
//查找一次位置,返回的是符合的下标位置
string s1 = "Kevin eqwKevin";
int index = s1.find("Kevin",0);
//查找全部的位置
string s2 = "Kevin duwKevin Keddq";
int offindex = s2.find("Kevin",0);
while(offindex != -1)
{
cout<<"offindex:"<<offindex<<endl;
offindex = offindex + 1;
offindex = s2.find("Kevin",offindex);
}
}
这里注意find返回值是下标位置,当找不到时候返回-1。
size_type find (value_type _Chr, size_type _Off = 0) const;
//find()函数的第1个参数是被搜索的字符、第2个参数是在源串中开始搜索的下标位置
size_type find (const value_type* _Ptr , size_type _Off = 0) const;
//find()函数的第1个参数是被搜索的字符串,第2个参数是在源串中开始搜索的下标位置
size_type find (const value_type* _Ptr, size_type _Off = 0, size_type _Count) const;
//第1个参数是被搜索的字符串,第2个参数是源串中开始搜索的下标,第3个参数是关于第1个参数的字符个数,可能是 _Ptr 的所有字符数,也可能是 _Ptr 的子串宇符个数
size_type find (const basic_string& _Str, size_type _Off = 0) const;
//第1个参数是被搜索的字符串,第2参数是在源串中开始搜索的下标位置
5.字符串替换
#include <iostream>
#include <string>
using namespace std;
void String_Replace()
{
string s1 = "asdaaajijfoeasd";
int index = s1.find('a',0);
while(index != -1)
{
cout<<index<<endl;
s1.replace(index,1,"A");
index = index +1 ;
index = s1.find('a',index);
}
cout<<s1<<endl;
}
6.字符串删除
#include <iostream>
#include <string>
#include "algorithm"
using namespace std;
void String_Delete()
{
string s1 = "dwsadaaffaa";
string::iterator it = find(s1.begin(),s1.end(),'a');
if(it != s1.end())
{
s1.erase(it);
}
}
7.字符串插入
#include <iostream>
#include <string>
using namespace std;
void String_Insert()
{
string s1 = "bbb";
s1.insert(0,"AAA"); //头插
s1.insert(s1.length(),"CCC"); //尾插
cout<<s1<<endl;
}