如何将字符串转换为大写。我从谷歌上找到的例子只涉及字符。


当前回答

我的解决方案(清除第6位):

#include <ctype.h>

inline void toupper(char* str)
{
    while (str[i]) {
        if (islower(str[i]))
            str[i] &= ~32; // Clear bit 6 as it is what differs (32) between Upper and Lowercases
        i++;
    }
}

其他回答

如果您只关心8位字符(除了Milan babukov以外的所有答案都假设),您可以通过在编译时使用元编程生成查找表来获得最快的速度。在ideone.com上,这比库函数快7倍,比手写版本快3倍(http://ideone.com/sb1Rup)。它也可以通过特征自定义,没有减速。

template<int ...Is>
struct IntVector{
using Type = IntVector<Is...>;
};

template<typename T_Vector, int I_New>
struct PushFront;
template<int ...Is, int I_New>
struct PushFront<IntVector<Is...>,I_New> : IntVector<I_New,Is...>{};

template<int I_Size, typename T_Vector = IntVector<>>
struct Iota : Iota< I_Size-1, typename PushFront<T_Vector,I_Size-1>::Type> {};
template<typename T_Vector>
struct Iota<0,T_Vector> : T_Vector{};

template<char C_In>
struct ToUpperTraits {
    enum { value = (C_In >= 'a' && C_In <='z') ? C_In - ('a'-'A'):C_In };
};

template<typename T>
struct TableToUpper;
template<int ...Is>
struct TableToUpper<IntVector<Is...>>{
    static char at(const char in){
        static const char table[] = {ToUpperTraits<Is>::value...};
        return table[in];
    }
};

int tableToUpper(const char c){
    using Table = TableToUpper<typename Iota<256>::Type>;
    return Table::at(c);
}

用例:

std::transform(in.begin(),in.end(),out.begin(),tableToUpper);

为了深入(多页)描述它是如何工作的,请允许我无耻地插入我的博客:http://metaporky.blogspot.de/2014/07/part-4-generating-look-up-tables-at.html

使用Boost。Text,它将适用于Unicode文本

boost::text::text t = "Hello World";
boost::text::text uppered;
boost::text::to_title(t, std::inserter(uppered, uppered.end()));
std::string newstr = uppered.extract();

不确定是否有内置功能。试试这个:

包括ctype.h或cctype库,以及stdlib.h作为预处理器指令的一部分。

string StringToUpper(string strToConvert)
{//change each element of the string to upper case
   for(unsigned int i=0;i<strToConvert.length();i++)
   {
      strToConvert[i] = toupper(strToConvert[i]);
   }
   return strToConvert;//return the converted string
}

string StringToLower(string strToConvert)
{//change each element of the string to lower case
   for(unsigned int i=0;i<strToConvert.length();i++)
   {
      strToConvert[i] = tolower(strToConvert[i]);
   }
   return strToConvert;//return the converted string
}

如果你只使用ASCII字符,速度会更快:

for(i=0;str[i]!=0;i++)
  if(str[i]<='z' && str[i]>='a')
    str[i]+='A'-'a';

请注意,这段代码运行得更快,但只适用于ASCII,不是一个“抽象”的解决方案。

其他UTF8字母的扩展版本:

...
if(str[i]<='z' && str[i]>='a') //is latin
    str[i]+='A'-'a';
else if(str[i]<='я' && str[i]>='а') //cyrillic
    str[i]+='Я'-'я'
else if(str[i]<='ω' && str[i]>='α') //greek
    str[i]+='Ω'-'ω'
//etc...

如果您需要完整的UNICODE解决方案或更传统和抽象的解决方案,请寻找其他答案并使用c++字符串的方法。

Boost字符串算法:

#include <boost/algorithm/string.hpp>
#include <string>

std::string str = "Hello World";

boost::to_upper(str);

std::string newstr = boost::to_upper_copy<std::string>("Hello World");