我正在寻找一种简单的方法将带有下划线的C ++字符串转换为camelCase,即: my_simple_humble_string 至 mySimpleHumbleString
Perl很容易。我不想使用boost。
答案 0 :(得分:2)
根据this site,不支持。找不到其他任何与之相矛盾的提示......
另一方面,手工制作并不困难:
def self.perform(*args)
if Rails.application.config.perform_later
perform_later(*args)
else
perform_now(*args)
end
end
修改:就地变体:
std::string camelCase(std::string const& input)
{
std::string s;
s.reserve(input.length());
bool isMakeUpper = false;
for(char c : input)
{
if(c == '_')
{
isMakeUpper = true;
}
else if(isMakeUpper)
{
s += (char)toupper(c);
isMakeUpper = false;
}
else
{
s += c;
}
}
return s;
}
编辑2:字符串的就地变体:
void camelCase(char* input)
{
bool isMakeUpper = false;
char* pos = input;
for(char* c = input; *c; ++c)
{
if(*c == '_')
{
isMakeUpper = true;
}
else if(isMakeUpper)
{
*pos++ = toupper(*c);
isMakeUpper = false;
}
else
{
*pos++ = *c;
}
}
*pos = 0;
}
答案 1 :(得分:-1)
应谨慎使用正则表达式,请参阅"Now you Have 2 Problems
这是不需要它们的一个很好的例子。鉴于SELECT * FROM (XXX) temp WHERE rank BETWEEN 80 AND 90
我们可以做到:
auto foo = "my_simple_humble_string"s
关于算法的几点说明:
auto count = 0;
for (auto read = 1; read < size(foo); ++read) {
if (foo[read] == '_') {
++count;
++read;
foo[read - count] = toupper(static_cast<unsigned char>(foo[read]));
} else {
foo[read - count] = foo[read];
}
}
foo[size(foo) - count] = foo[size(foo)];
foo.resize(size(foo) - count);
读取,这是C ++ 11之前未定义的行为:http://en.cppreference.com/w/cpp/string/basic_string/operator_at