关于我们

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻公共列表

C和C++中char类型和String类型大小写转换的方法

发布时间:2020-01-16 17:16:17

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

1. char 大小写转换

#include <iostream>  

#include <string>  

#include <string.h> 

for (char* ptr = the_str; *ptr; ptr++) {  

    *ptr = tolower(*ptr);  //转小写

    //*ptr = toupper(*ptr);  //转大写

  }  

2. string大小写转换

 #include <string>  

 #include <algorithm> 

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);

1

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

对‘transform(__gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, __gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, __gnu_cxx::__normal_iterator<char*,

std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, <unresolved overloaded function type>)’ 的调用没有匹配的函数。

这里出现错误的原因是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);

1

或者:

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

1

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


3.char * 大小写转换

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


#include <string>  

#include <algorithm> 

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());



/template/Home/Zkeys/PC/Static