字符/字符串的处理在程序中是较为常见的,也是比较重要的一块。
例子,将给定的字符串中的字母全部转成大写字母。如将“Hello, I'm 3 years old.”转换成“HELLO, I'M 3 YEARS OLD.”
以前的解决方法是:使用for循环逐个的操作每个字符。
#include <iostream>
#include <string>
using namespace std;
string trans2uppercase(string source)
{
string rslt = "";
for(string::iterator iter = source.begin(); iter != source.end(); ++iter)
{
rslt += toupper(*iter);
}
return rslt;
}
int main()
{
string my_string = "Hello, I'm 3 years old.";
cout << trans2uppercase(my_string) << endl;
return 0;
}
而C++11之后,我们可以直接调用std::transform,一句话搞定。
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string my_string = "Hello, I'm 3 years old.";
std::transform(my_string.begin(), my_string.end(), my_string.begin(), ::toupper);
cout << my_string << endl;
return 0;
}