C++ string的大小寫轉換


 將一個string轉換成大寫或者小寫,是項目中經常需要做的事情,但string類里並 沒有提供這個方法。自己寫個函數來實現,說起來挺簡單,但做起來總讓人覺得不方便。打個比方:早上起來想吃個漢堡,冰箱里有生牛肉,有面粉,也有微波爐, 是可以自己做的,但是實在是太費事,沒幾個人願意做。但是,打個電話給肯德基宅急送,10分鍾后就有熱乎乎的漢堡送上門了,大大節省了時間(時間就是金 錢,你可以將時間用在更重要的開發工作上),並且味道也不差,何樂而不為呢?

       STL的algorithm庫確實給我們提供了這樣的便利,使用模板函數transform可以輕松解決這個問題,開發人員只需要提供一個函數對象,例如將char轉成大寫的toupper函數或者小寫的函數tolower函數。


transform原型:

    template < class InputIterator, class OutputIterator,
 class UnaryOperator >  
      OutputIterator transform ( InputIterator first1, InputIterator last1,  
                                 OutputIterator result, UnaryOperator op );  
      
    template < class InputIterator1, class InputIterator2,  
               class OutputIterator, class BinaryOperator >  
      OutputIterator transform ( InputIterator1 first1, InputIterator1 last1,  
                                 InputIterator2 first2, OutputIterator result,  
                                 BinaryOperator binary_op );  

測試代碼:

 1 #include <string>  
 2 #include <algorithm>  
 3 using namespace std;  
 4       
 5 int main()  
 6 {  
 7         string strA = "yasaken@126.com";  
 8         string strB = "LURY@LENOVO.com";  
 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:yasaken@126.com   
 2 strB:LURY@LENOVO.com   
 3   
 4 After transform to toupper:  
 5 strA:YASAKEN@126.COM   
 6 strB:LURY@LENOVO.COM   
 7   
 8 After transform to lower:  
 9 strA:yasaken@126.com   
10 strB:lury@lenovo.com
   轉載自:http://blog.csdn.net/zhongyhc/article/details/41686893。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM