C++ STL 迭代器在string类中的使用方法

//以下例子说明迭代器在string类中的使用方法
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

int main()
{
    string s("Hello World! I love programming!");
    cout<<s<<endl;
    //用s初始化sd
    string sd(s.begin(),s.end());
    cout<<sd<<endl;
    //将sd的所有内容转化为大写,::toupper意为使用全局中的toupper函数
    transform(sd.begin(),sd.end(),sd.begin(),::toupper);
    cout<<sd<<endl;
    string sd1;
    //将sd的部分内容追加到sd1中
    sd1.append(sd.begin(),sd.end()-7);
    cout<<sd1<<endl;
    string sd2;
    string::reverse_iterator iterA;
    string temp="0";
    //逆序遍历sd,并将sd内容追加到sd2中
    for(iterA=sd.rbegin();iterA!=sd.rend();iterA++){
        temp=*iterA;
        sd2.append(temp);
    }
    cout<<sd2<<endl;
    //去除sd2 0到15位内容
    sd2.erase(0,15);
    cout<<sd2<<endl;
    string::iterator iterB=sd2.begin();
    string sd3=string("12345678");
    //插入sd3
    sd2.insert(iterB,sd3.begin(),sd3.end());
    cout<<sd2<<endl;
    //替换字符串
    sd2.replace(sd2.begin(),sd2.end(),"This is an Example of Replace!");
    cout<<sd2<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/ibelievesunshine/article/details/80208081