본문 바로가기
연습장

Convert string to camel case

by anothel 2021. 10. 19.

Complete the method/function so that it converts dash/underscore delimited words into camel casing. The first word within the output should be capitalized only if the original word was capitalized (known as Upper Camel Case, also often referred to as Pascal case).

 

Examples

"the-stealth-warrior" gets converted to "theStealthWarrior"
"The_Stealth_Warrior" gets converted to "TheStealthWarrior"

 

Solution

#include <string>

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

  bool bCheck = false;

  for (auto x : text) {
    if (x == '-' || x == '_') {
      bCheck = !bCheck;
      continue;
    }   

    if (bCheck == true) {
      result += std::toupper(x);
      bCheck = !bCheck;
    } else {
      result += x;      
    }
  }

  return result;
}

 

ZSNO의 코드

#include <string>

std::string to_camel_case(std::string text)
{
  for(int i = 0; i < text.size(); ++i)
  {
    if(text[i] == '-' || text[i] == '_')
    {
      text.erase(i,1);
      text[i] = toupper(text[i]);
    }
  }
  return text;
}

 

 

chris_w의 코드

#include <string>

std::string to_camel_case(const std::string & text)
{
    std::string result;
    result.reserve(text.length());

    bool capital = false;

    for (auto c : text)
    {    
        // any non-alphanumeric character causes the next one to be upper-case
        if (!std::isalpha(c))
        {
            capital = true;
        }
        
        // this character should be upper case if the "capital" flag is set or if
        // it's already an upper-case character
        else if (capital || std::isupper(c))
        {
            result.push_back(std::toupper(c));
            capital = false; // unset the "capital" flag after emitting the character
        }
        
        // anything else is emitted as lower case
        else
        {
            result.push_back(std::tolower(c));
        }
    }
    
    return result;
}

 

후기

bool 자료형에서 !(not) 연산자보다는 ^(xor) 연산자를 사용하고 싶었는데 무언가 잘못 알고 있던 개념인 것 같다. 그래서 다시 알아봤다. XOR연산자는 같으면 1 다르면 0을 반환한다. 이게 답이다.

1번 아저씨는 낙타 표기법의 정석을 따랐다. 대시나 언더 바가 나오면 이후는 대문자로 치환. 사실 내가 짠 설루션보다는 좀 더 직관적이고 명확하다. 잘 짠 코드. 2번 아저씨는 대검으로 마늘을 편 썰었다. 주석까지 완벽하게. 알파벳이 아니면 대시나 언더바 일 것이고 다음 for 문에서 대문자 혹은 소문자 출력. 완벽하다.

 

(url: https://www.codewars.com/kata/517abf86da9663f1d2000003)

 

728x90

'연습장' 카테고리의 다른 글

Playing with digits  (0) 2021.10.21
Bit Counting  (0) 2021.10.19
Sum of Digits / Digital Root  (0) 2021.10.19
Find the odd int  (0) 2021.10.19
Split Strings  (0) 2021.10.19