QUESTIONS

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

  elmarki       2021/09/06       145


145

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..

asked
2 answers
145 votes

SOLUTIONS: (2)

0
      18

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).

0
      18

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] == '_')
      {
        ++removedChars;
        convert = true;
        continue;
      }
      text[loop - removedChars] = converter[convert](text[loop]);
      convert = false;
  }
  text.resize(text.size() - removedChars);
  return text;
}

QUESTIONS:


Nfiles Questions - nfiles.xyz the Q nad A blogs sites for free
🗂 Nfiles » Home
🗂 ModStore
🗂 Videos
🗂 Shareurl
🗂 About us
🗂 Bitcoin

Connecting...
👤 Mr. snow finger
👤 Yoki No moto
👤 Xdeveloper
👤 Malitanyo Dev
👤 Money Motto
👤 Ako Johnny Sin
Create with ❤ Questions by nfiles.xyz 2021