linux C/C++大小写转换

linux C/C++中,只有char的大小写转换,没有char*的大小写转化,string的大小写转换通过char的大小写转换完成

1. char 大小写转换

#include   
#include   
#include  
for (char* ptr = the_str; *ptr; ptr++) {  
    *ptr = tolower(*ptr);  //转小写
    //*ptr = toupper(*ptr);  //转大写
  }  

tolower/toupper只能用于单个字符转换,不能用于字符串转换。

2. string大小写转换

 #include   
 #include  
transform(str.begin(), str.end(), str.begin(), (int (*)(int))tolower);//转小写
//transform(str.begin(), str.end(), str.begin(), ::tolower);//转小写两种方式都可以
transform(str.begin(), str.end(), str.begin(), (int (*)(int))toupper);//转大写

不能直接使用:

transform(str.begin(), str.end(), str.begin(),tolower);

但在使用g++编译时会报错:

对‘transform(__gnu_cxx::__normal_iterator, std::basic_string, std::char_traits, std::allocator > >, __gnu_cxx::__normal_iterator, std::basic_string, std::char_traits, std::allocator > >, __gnu_cxx::__normal_iterator,
std::basic_string, std::char_traits, std::allocator > >, )’ 的调用没有匹配的函数。
这里出现错误的原因是Linux将toupper实现为一个宏而不是函数:
/usr/lib/syslinux/com32/include/ctype.h:
/* Note: this is decimal, not hex, to avoid accidental promotion to unsigned */
#define _toupper(__c) ((__c) & ~32)
#define _tolower(__c) ((__c) | 32)
__ctype_inline int toupper(int __c)
{
return islower(__c) ? _toupper(__c) : __c;
}
__ctype_inline int tolower(int __c)
{
return isupper(__c) ? _tolower(__c) : __c;
}

两种解决方案:
第一种:

transform(str.begin(), str.end(), str.begin(), (int (*)(int))toupper);

或者:

transform(str.begin(), str.end(), str.begin(), ::toupper);

第二种:自己实现tolower//tolower的函数

3.char * 大小写转换

char*的大小写转换string过度完成大小写的转换过程

#include   
#include  
char *tok;
string str=posParse;
const int len = str.length();
tok = new char[len+1];
transform(str.begin(), str.end(), str.begin(), (int (*)(int))tolower);//转小写
//transform(str.begin(), str.end(), str.begin(), ::tolower);//转小写两种方式都可以
transform(str.begin(), str.end(), str.begin(), (int (*)(int))toupper);//转大写
strcpy(tok,str.c_str());

你可能感兴趣的:(C/C++,linux,string,linux,大小写转换,C,C++)