代码之家  ›  专栏  ›  技术社区  ›  Adam

C++中的下/上字符串

  •  24
  • Adam  · 技术社区  · 16 年前

    在C++中,人们发现字符串到小写字母/大写字母的最好方式是什么?

    这个问题很复杂,因为C++不是一个纯英语的编程语言。有好的多语言方法吗?

    9 回复  |  直到 16 年前
        1
  •  27
  •   Darren Kopp    11 年前
    #include <algorithm>
    std::string data = "Abc";
    std::transform(data.begin(), data.end(), data.begin(), ::toupper);
    

    http://notfaq.wordpress.com/2007/08/04/cc-convert-string-to-upperlower-case/

    此外,常见字符串方法的代码项目文章: http://www.codeproject.com/KB/stl/STL_string_util.aspx

        2
  •  20
  •   GManNickG    14 年前
    > std::string data = “Abc”; 
    > std::transform(data.begin(), data.end(), data.begin(), ::toupper);
    

    这将有效,但这将使用标准的“c”区域设置。如果需要为另一个区域设置ToLower,可以使用facets。上面使用方面的代码是:

    locale loc("");
    const ctype<char>& ct = use_facet<ctype<char> >(loc);
    transform(str.begin(), str.end(), std::bind1st(std::mem_fun(&ctype<char>::tolower), &ct));
    
        3
  •  6
  •   user201133    15 年前

    对于希望使用nic strong答案的复制粘贴程序,请注意“use factet”中的拼写错误以及std::transform缺少的第三个参数:

    locale loc("");
    const ctype<char>& ct = use_factet<ctype<char> >(loc);
    transform(str.begin(), str.end(), std::bind1st(std::mem_fun(&ctype<char>::tolower), &ct));
    

    应该是

    locale loc("");
    const ctype<char>& ct = use_facet<ctype<char> >(loc);
    transform(str.begin(), str.end(), str.begin(), std::bind1st(std::mem_fun(&ctype<char>::tolower), &ct));
    
        4
  •  4
  •   Community pid    7 年前

    你也应该复习 this question . 基本上问题是标准的C/C++库不是用来处理Unicode数据的,所以你必须查看其他库。

    这可能随着C++标准的更新而改变。我知道Borland(Code Goice)的下一个编译器将有Unicode支持,我猜想微软的C++编译器将拥有或已经拥有支持Unicode的字符串库。

        5
  •  2
  •   Steve Gury    16 年前

    正如Darren告诉您的,最简单的方法是使用std::transform。

    但要注意,在某些语言中,例如德语,并不总是在小写和大写之间有一对一的映射。“esset”小写字符(看起来像希腊字符beta)以大写形式转换为“ss”。

        6
  •  2
  •   yasouser    14 年前

    如果你有动力,那么它有最简单的方法。看一看 to_upper()/to_lower() in Boost string algorithms .

        7
  •  1
  •   NoOne    11 年前

    我找到了一种转换Unicode(和多语言)字符大小写的方法,但您需要知道/找到(不知何故)字符的区域设置:

    #include <locale.h>
    
    _locale_t locale = _create_locale(LC_CTYPE, "Greek");
    AfxMessageBox((CString)""+(TCHAR)_totupper_l(_T('α'), locale));
    _free_locale(locale);
    

    我还没找到办法…我有人知道怎么做,告诉我。

    将区域设置为空不起作用…

        8
  •  1
  •   James Oravec    11 年前

    这个 VCL 有一个 SysUtils.hpp 哪个有 LowerCase(unicodeStringVar) UpperCase(unicodeStringVar) 可能对你有用。我在C++ Builder 2009中使用这个。

        9
  •  0
  •   axs6791    16 年前

    史蒂夫说的是对的,但是我想如果你的代码必须支持几种语言,你可以有一个工厂方法,它封装了一组方法,这些方法基于这种语言来完成相关的toupper或tolower。