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

。_饼干妹妹 提交于 2019-12-02 15:35:56

以下的用法中包括:复制、小写变大写、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;
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!