I am looking for a simple way to turn C++ strings with underscores to camelCase, i.e.: my_simple_humble_string to mySimpleHumbleString
Easy in Perl. I prefer not to use boost.
I am looking for a simple way to turn C++ strings with underscores to camelCase, i.e.: my_simple_humble_string to mySimpleHumbleString
Easy in Perl. I prefer not to use boost.
According to this site, it is not supported. Could not find any other hints contradicting...
On the other hand, it is not too difficult to do it by hand:
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;
}
Edit: in-place variant:
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;
}
Edit 2: in-place variant for strings:
void camelCase(std::string& input)
{
bool isMakeUpper = false;
std::string::iterator pos = input.begin();
for(char c : input)
{
if(c == '_')
{
isMakeUpper = true;
}
else if(isMakeUpper)
{
*pos++ = (char)toupper(c);
isMakeUpper = false;
}
else
{
*pos++ = c;
}
}
input.resize(pos - input.begin());
}
Regexes should be used sparingly, see "Now you Have 2 Problems
This is a good example of a case where they are not needed. Given auto foo = "my_simple_humble_string"s
we can do:
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);
A couple notes on the algorithm:
foo[size(foo)]
which is undefined behavior prior to C++11: http://en.cppreference.com/w/cpp/string/basic_string/operator_at