linux C/C++大小寫轉換
阿新 • • 發佈:2019-02-10
linux 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); //轉大寫
}
tolower/toupper只能用於單個字元轉換,不能用於字串轉換。
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);
但在使用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);
或者:
transform(str.begin(), str.end(), str.begin(), ::toupper);
第二種:自己實現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());