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