我想转换一个std::字符串小写。我知道tolower()函数。然而,在过去,我有这个函数的问题,它几乎不是理想的无论如何使用std::string将需要迭代每个字符。
有没有一种替代方案能100%有效?
我想转换一个std::字符串小写。我知道tolower()函数。然而,在过去,我有这个函数的问题,它几乎不是理想的无论如何使用std::string将需要迭代每个字符。
有没有一种替代方案能100%有效?
当前回答
// tolower example (C++)
#include <iostream> // std::cout
#include <string> // std::string
#include <locale> // std::locale, std::tolower
int main ()
{
std::locale loc;
std::string str="Test String.\n";
for (std::string::size_type i=0; i<str.length(); ++i)
std::cout << std::tolower(str[i],loc);
return 0;
}
欲了解更多信息:http://www.cplusplus.com/reference/locale/tolower/
其他回答
我写了这个简单的helper函数:
#include <locale> // tolower
string to_lower(string s) {
for(char &c : s)
c = tolower(c);
return s;
}
用法:
string s = "TEST";
cout << to_lower("HELLO WORLD"); // output: "hello word"
cout << to_lower(s); // won't change the original variable.
为ASCII字符串to_lower添加了一些可选库,它们都是生产级的,并进行了微优化,预计会比这里现有的答案更快(TODO:添加基准测试结果)。
Facebook的愚蠢:
void toLowerAscii(char* str, size_t length)
谷歌的绳降:
void AsciiStrToLower(std::string* s);
使用c++ 11中基于范围的for循环,代码会更简单:
#include <iostream> // std::cout
#include <string> // std::string
#include <locale> // std::locale, std::tolower
int main ()
{
std::locale loc;
std::string str="Test String.\n";
for(auto elem : str)
std::cout << std::tolower(elem,loc);
}
使用fplus库中的fplus::to_lower_case()。
在fplus API搜索中搜索到_lower_case
例子:
fplus::to_lower_case(std::string("ABC")) == std::string("abc");
代码片段
#include<bits/stdc++.h>
using namespace std;
int main ()
{
ios::sync_with_stdio(false);
string str="String Convert\n";
for(int i=0; i<str.size(); i++)
{
str[i] = tolower(str[i]);
}
cout<<str<<endl;
return 0;
}