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

本文通过一个具体的C++程序示例介绍了如何使用迭代器来操作标准库中的string对象,包括大小写转换、逆序复制、插入和替换等操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//以下例子说明迭代器在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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值