C C++ 字符串大小寫轉換

在C++中,由於沒有單獨定義string這個對象,所以字符串的操作比較麻煩些。
字符串轉換大小寫是一個常用的功能,今天就簡單總結下常用轉換的方法:

 由於ANSI和Unicode在函數名上有差別,故都列出來,不過本人以Unicode爲主。

 

 【1. 用C語言標準庫函數 toupper, tolower】
 頭文件:cctype   c下面:ctype.h
 轉大寫
 Ansi版: int toupper(int c);</a>
 Unicode版:int towupper(wint_t c);
 MSDN: toupper, _toupper, towupper, _toupper_l, _towupper_l

 轉小寫:
 int tolower(
    int c
 );

 int towlower(
    wint_t c
 );

 MSDN:tolower

 缺陷:只能轉換單個字符

 Example:

      WCHAR wch = 'a';
       wch = towupper(wch); // A

 

 【2. 用C++語言標準庫函數 _strlwr_s,  _strupr_s】
 注意:要使用安全的字符串函數,不要用_strlwr。
 頭文件:string.h
 轉小寫:
 Ansi:
 errno_t _strlwr_s(
    char *str,
    size_t numberOfElements
 );

 Unicode:
 errno_t _wcslwr_s(
    wchar_t *str,
    size_t numberOfElements
 );

 注意:numberOfElements 要加上最後NULL字符長度,即numberOfElements = strlen(str) + 1;

 MSDN:http://msdn.microsoft.com/en-us/library/y889wzfw(VS.80).aspx

 轉大寫:
 errno_t _strupr_s(
    char *str,
    size_t numberOfElements
 );

 errno_t _wcsupr_s(
    wchar_t * str,
    size_t numberOfElements
 );

 MSDN: http://msdn.microsoft.com/en-us/library/sae941fh(VS.80).aspx

 Example:

     WCHAR wideStr[] = L"Abc";
     _wcslwr_s(wideStr, wcslen(wideStr) + 1); // abc  轉化後的小寫字符串存在wideStr中
    _wcsupr_s(wideStr, wcslen(wideStr) + 1);// ABC  轉化後的大寫字符串存在wideStr中

 

 【3. std::string 轉換大小寫】
 很遺憾,std::string 沒有提供大小寫轉換的功能,所以只能用STL中的transform結合toupper/tolower完成。
 頭文件: string, cctype,algorithm
 轉小寫:
  transform(str.begin(),str.end(),str.begin(),tolower);
 transform(wstr.begin(), wstr.end(), wstr.begin(), towlower);
 轉大寫:
 transform(s.begin(), s.end(), s.begin(), toupper);
 transform(wstr.begin(), wstr.end(), wstr.begin(), towupper);

 Example:
     wstring wstr =L"Abc";
     transform(wstr.begin(), wstr.end(), wstr.begin(), towupper);

 

 【4.boost庫中string_algorithm 提供了大小寫轉換函數 to_lower 和 to_upper】

 Example:
 #include <boost/algorithm/string.hpp>   
 using namespace std;   
 using namespace boost;

 wstring wstr =L"Abc";
 boost::to_lower(wstr); // abc

 ====================================================================
   附完整Example

   **
  * @file     test.cpp
  * @brief    字符大小寫轉換
  * @author   [email protected]
  * @date     2009-7-1
  */

  #include "stdafx.h"
  #include <cstring>
  #include <windows.h>
  #include <cctype>
  #include <algorithm>
  #include "boost/algorithm/string.hpp"
  using namespace std;

 int wmain(int argc, WCHAR* argv[])
 {
     char ch = 'a';
     ch = toupper(ch);

     WCHAR wch = 'a';
     wch = towupper(wch);

     WCHAR wideStr[] = L"Abc";
     _wcslwr_s(wideStr, wcslen(wideStr) + 1);

     _wcsupr_s(wideStr, wcslen(wideStr) + 1);

     wstring wstr =L"Abc";
     transform(wstr.begin(), wstr.end(), wstr.begin(), towupper);

     boost::to_lower(wstr);

     return 0;
 }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章