16 Jun 2020

Convert a snake case to a camel case

  • algorithm
  • string
  • Naver_webtoons
  • interview
  • Problem

    Convert from snake-case to camel-case and return it.

    Example

    input: 
    naver_webtoon
    NAVER_WEBTOON
    
    output:
    naverWebtoon
    naverWebtoon
    written in C++

    Solution 1

    1. loop through the snake case string
    2. As iterationg, have a boolean ‘cap’ and update it if there is a underdash to convert the next letter to cap
      Time Complexity = O(n)
    
    
    string convertCamel(string snake){
        string camel;
        bool cap = false;
        for(char c : snake){
            if(!cap && (int)c < 91){//if the char is cap when it shouldn't be
                camel.push_back(tolower(c)); 
            }else if(c == '_'){//if there is an underdash, the next char should be capitalized
                cap = true;
            }else if(cap){//if there should be a cap char convert the char to cap if it is not. Else, just push it back
                if((int)c > 97){
                    camel.push_back(toupper(c));
                }else{
                    camel.push_back(c);
                }
                cap = false;
            }else{
                camel.push_back(c);
            }
        }
        return camel;
    }