string大小寫轉換函式 分類: C/C++/C# 2010-09-25 15:38 1495人閱讀 評論(0) 收藏 舉報stringbasicalgorithmc多線程function
最近被多線程+野指標折磨ING……
C++中沒有string直接轉換大小寫函數,需要自己實現。一般來講,可以用stl的algorithm實現:
#include <iostream>
#include <cctype>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string s = "ddkfjsldjl";
transform(s.begin(), s.end(), s.begin(), toupper);
cout<<s<<endl;
return 0;
}
但在使用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;
}
兩種解決方案:
1.transform(str.begin(), str.end(), str.begin(), (int (*)(int))toupper);
這裡(int (*)(int))toupper是將toupper轉換為一個傳回值為int,參數只有一個int的函數指標。
2.自己實現ToUpper函數:
int ToUpper(int c)
{
return toupper(c);
}
transform(str.begin(), str.end(), str.begin(), ToUpper);
附:大小寫轉換函式
#include <cctype>
#include <string>
#include <algorithm>
using namespace std;
void ToUpperString(string &str)
{
transform(str.begin(), str.end(), str.begin(), (int (*)(int))toupper);
}
void ToLowerString(string &str)
{
transform(str.begin(), str.end(), str.begin(), (int (*)(int))tolower);
}