是否可以使std :: string始终保持小写字符串?

Avi*_*hek 6 c++ string boost stl

是否可以使std :: string始终保持小写字符串?这是我将如何使用它:

typedef std::basic_string<...> lowercase_string;

void myfunc()
{
  lowercase_string s = "Hello World"; // notice mixed case
  printf(s.c_str());                  // prints "hello world" in lowercase
  std::string s2 = s;
  printf(s2.c_str());                 // prints "hello world" in lowercase
}
Run Code Online (Sandbox Code Playgroud)

Naw*_*waz 18

您可以编写自己的char特征并将其std::basic_string作为第二个模板参数传递给它.

这是一个最小的例子:

template<typename T>
struct lowercase_char_traits : std::char_traits<T>
{
    static T* copy(T* dest, const T* src, std::size_t count )
    {
         for(size_t i = 0 ; i < count ; ++i)
              dest[i] = std::tolower(src[i]);
         return dest;
    }
    static void assign(T & out, T in)
    {
       out = std::tolower(in);
    }
    //implement other overload of assign yourself

    //note that you may have to implement other functionality 
    //depending on your requirement
};
Run Code Online (Sandbox Code Playgroud)

然后将typedef定义为:

typedef std::basic_string<char, lowercase_char_traits<char>> lowercase;
Run Code Online (Sandbox Code Playgroud)

这是一个测试程序:

int main() 
{
    lowercase s1 = "Hello World";
    std::cout << s1.c_str() << std::endl;

    lowercase s2 = "HELLO WORLD";
    std::cout << std::boolalpha << (s1 == s2) << std::endl;

    lowercase s3 = "HELLO";
    s3 += " WorL";
    s3.append("D");
    std::cout << std::boolalpha << (s1 == s3) << std::endl;

    std::cout << s2.c_str() << std::endl;
    std::cout << s3.c_str() << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

输出:

hello world
true
true
hello world
hello world
Run Code Online (Sandbox Code Playgroud)

很酷,不是吗?


请注意,要使用完全工作的小写字符串类,您可能还需要定义其他功能lowercase_char_traits,具体取决于您希望从此类中执行的操作.

有关详细信息和解释,请查看Herb Sutter精彩文章:

希望有所帮助.

  • 请注意,使用它时,如果希望`lowercase`表现一致,您可能还需要实现小写的`lt`,`eq`和`compare`. (2认同)