您的位置:首页 > 编程语言 > C语言/C++

c++ STL string一些总结

2016-06-23 18:05 399 查看
字符串是常见的操作之一,熟练地运用一些常见的字符数组和字符串操作,有时能够大大提高效率。因此,简答学习了一下。其实,其本身也可以看做是容器。因此很多操作与一些STL的常见操作类似。主要通过程序实现的方式。具体可见代码。
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main(int argc, const char * argv[]) {
//读入
string s;
//cin >> s; ////当用cin>>进行字符串的输入的时候,遇到空格的地方就停止字符串的读取输入
//cin.get();
getline(cin,s);//以回车分开
cout << s << endl;
//赋值(略去一些append、assign)
string str1;
str1="yesterday once more";
string str2 (str1,6);// = day once more
string str3 (str1,6,3);//= day

char ch[] = {"Roly-Poly"};
string str4 = ch;
string str5 (ch);
string st6 (ch,4);//=Roly
string str7 (10,'i'); // =iiiiiiiiiii
string str8 (ch+5,ch+9); //Poly

string str9;
str9=str1+str3;

str9.insert(6,"!!!");//从第6个位置插入!!!
cout << str9 << endl;

string::iterator it;
for (it=str9.begin();it!=str9.end();++it)
cout << * it;

if (str1>str2)
cout << "Yes" << endl;
else
cout << "No" <<endl;

//sort、find、replace、erase...
sort(str9.begin(),str9.end());

string::size_type position;
position = str1.find("day");//find函数返回day在str1中第一次出现的下标位置

string str10="zy01zy02zy03zyzyzy";
position = str10.find("zy");
if (position!=str10.npos)//如果没找到,返回npos,这是一个很大的值
{
cout << position << endl;
}
position = str1.find("day",7);//从str1的下标7开始,查找字符串day
if (position!=str1.npos)//如果没找到,返回npos,这是一个很大的值
{
cout << position << endl;
}

position = 0;
while ((position=str10.find("zy",position))!= str10.npos)
{

cout << position << endl;
position++;
}

str4.swap(str5);//交换

str10.replace(6,str1.length(),str1);

cout << str10 << endl;

str7.erase();//清空
cout << str1 << endl;
str1.erase(2,4);//删除从2开始,长度为4的字符串
cout << str1 << endl;

string str11 = "hi, this is Rachel Greeen";
cout << str11 << endl;
int k = str11.find_first_of("aeiou");//find_first_of 函数最容易出错的地方是和find函数搞混。它最大的区别就是如果在一个字符串str1中查找另一个字符串str2,如果str1中含有str2中的任何字符,则就会查找成功,而find则不同
while (k!=string::npos)
{
str11[k]='*';
k=str11.find_first_of("aeiou", k+1,3);//第三个参数代表aeiou的前3个字符,即不带上o
}
cout << str11 << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  解题报告 string stl