您的位置:首页 > 编程语言 > C语言/C++

c++字符串大小写转换

2012-01-12 11:27 411 查看
在C++中,由于没有单独定义string这个对象,所以字符串的操作比较麻烦些。
字符串转换大小写是一个常用的功能,今天就简单总结下常用转换的方法:

由于ANSI和Unicode在函数名上有差别,故都列出来,不过本人以Unicode为主。

【1.用C语言标准库函数toupper,tolower】

头文件:cctype c下面:ctype.h

转大写

Ansi版: int toupper(int c);

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

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

【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 greenerycn@gmail.com

* @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;

}
http://www.cnblogs.com/Lynn_doo/articles/1663923.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: