Codewars Kata: Converting snake_case identifiers to CamelCase in C++

  elmarki       2021/09/06       55


The question and answer about this post on Codewars Kata: Converting snake_case identifiers to CamelCase in C++ have a total of 2 answer so far..

2 answers
55 votes



This is unnecessarily slow in at least a couple of different ways.

  1. Your algorithm is O(N²), but there are easy O(N) algorithms.
  2. You copy the input string unnecessarily. You could easily pass it by reference.

It's O(N²) because easy time you encounter a - or _, you copy the entire rest of the string to delete that one element. You can (for one example) just keep track of a "source" position and a "destination" position, copying elements from source to destination, skipping the ones you don't want, and capitalizing as needed. Then when you've copied all you need, you can eliminate all the ones you no longer need at once (all from the end, so you don't need to copy others after them).


Expanding on Jerry's answer. You have:

std::string to_camel_case(std::string text) {
  for (auto it = text.begin(); it != text.end(); it++)
      if (*it == '-' || *it == '_')
        it = text.erase(it);    // This line has a hidden loop.
                                // You are basically looping over
                                // the whole string and moving all
                                // the characters down one place.
        *it = toupper(*it);
  return text;

You want to re-write this removing the extra loop:

std::string to_camel_case(std::string text) {

  static const std::function<char(unsigned char)> converter[2] = {
      [](unsigned char x){return x;},
      [](unsigned char x){return std::toupper(x);}

  std::size_t removedChars = 0;
  bool        convert      = false;
  for (auto loop = 0u; loop < text.size(); ++loop)
      if (text[loop] == '-' || text[loop] == '_')
        convert = true;
      text[loop - removedChars] = converter[convert](text[loop]);
      convert = false;
  text.resize(text.size() - removedChars);
  return text;



Nfiles Questions - the Q nad A blogs sites for free
๐Ÿ—‚ Nfiles ยป Home
๐Ÿ—‚ ModStore
๐Ÿ—‚ Videos
๐Ÿ—‚ Shareurl
๐Ÿ—‚ About us
๐ŸŒ Malitanyo
๐ŸŒ Tagalog Anime 143 ๐Ÿ‘ค Mr. snow finger
๐Ÿ‘ค Yoki No moto
๐Ÿ‘ค Xdeveloper
๐Ÿ‘ค Malitanyo Dev
๐Ÿ‘ค Money Motto
๐Ÿ‘ค Ako Johnny Sin
Create with โค Questions by 2021