STL的algorithm库确实给我们提供了这样的便利,使用模板函数transform可以轻松解决这个问题,开发人员只需要提供一个函数对象,例如将char转成大写的toupper函数或者小写的函数tolower函数。
transform原型:
1 #include <string> 2 #include <algorithm> 3 using namespace std; 4 5 int main() 6 { 7 string strA = "[email protected]"; 8 string strB = "[email protected]"; 9 printf("Before transform:\n"); 10 printf("strA:%s \n", strA.c_str()); 11 printf("strB:%s \n\n", strB.c_str()); 12 13 transform(strA.begin(), strA.end(), strA.begin(), ::toupper); 14 transform(strB.begin(), strB.end(), strB.begin(), ::toupper); 15 printf("After transform to toupper:\n"); 16 printf("strA:%s \n", strA.c_str()); 17 printf("strB:%s \n\n", strB.c_str()); 18 19 transform(strA.begin(), strA.end(), strA.begin(), ::tolower); 20 transform(strB.begin(), strB.end(), strB.begin(), ::tolower); 21 printf("After transform to lower:\n"); 22 printf("strA:%s \n", strA.c_str()); 23 printf("strB:%s \n\n", strB.c_str()); 24 return 0; 25 }
运行结果:
1 strA:[email protected] 2 strB:[email protected] 3 4 After transform to toupper: 5 strA:[email protected] 6 strB:[email protected] 7 8 After transform to lower: 9 strA:[email protected] 10 strB:[email protected]
转载自:http://blog.csdn.net/zhongyhc/article/details/41686893。
时间: 2024-10-14 05:27:29