string大小寫轉換函式

來源:互聯網
上載者:User

string大小寫轉換函式 - 流水不爭先 - 部落格頻道 - CSDN.NET

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.