C++中的迭代器---进行操作字符串的基本用法

以下的用法中包括:复制、小写变大写、append追加、进行翻转字符串、进行擦除和替换的用法

以下引入一个比较重要的库:#include <algorithm>

1、复制用法:

#include <iostream>
#include <stdio.h>
#include <string>
#include <algorithm>

using namespace std;

int main()
{
    string s("are you beautiful");
    cout << "original:" << s << endl;
    string sd(s.begin(), s.end());//从最初到最后开始进行复制
    cout << "sd=" << sd << endl;
    while (1);
    return 0;

}

2、将字符串中的小写变成大写的用法

#include <iostream>
#include <stdio.h>
#include <string>
#include <algorithm>

using namespace std;

int main()
{
    string s("are you beautiful");
    cout << "original:" << s << endl;
    transform(s.begin(), s.end(), s.begin(), toupper); //使字符串中的小写变成大写
    cout << "s=" << s << endl;
    while (1);
    return 0;

}

3、将字符串进行翻转,如ABC-->CBA

#include <iostream>
#include <stdio.h>
#include <string>
#include <algorithm>

using namespace std;

int main()
{
    string s("ABC");
    string sd;
    string::reverse_iterator iterA;
    string temp = "0";
    for (iterA = s.rbegin(); iterA != s.rend(); iterA++) //将字符串进行翻转如:ABC->CBA
    {
        temp = *iterA;
        sd.append(temp);
    }
    cout << "sd=" << sd << endl;
    while (1);
    return 0;
}

4、进行擦除和进行替换的用法

#include <iostream>
#include <stdio.h>
#include <string>
#include <algorithm>

using namespace std;

int main()
{
    string s("ABC");
    s.erase(0, 2); //erase表示从第0个数开始,总共要去除的数目是2个
    cout << "s=" << s << endl;
    string sd = s.replace(s.begin(), s.end(), "This is an Replace");
    cout << "sd2.replace =" << sd;
    while (1);
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值