JadenCase 문자열 만들기

Falcon·2021년 2월 15일
1

programmers

목록 보기
13/27

🔒 문제

💭 생각의 흐름

(1) 공백 문자를 delimiter로 지정하여 split 하여 단어 단위로 담긴 배열을 생성하자
(2) 모든 단어 배열의 단어 첫글자만 대문자로 변환하자

💫😵 실수

  • 공백이여러개 연속해서 " a dkdm dkd" 입력될 수 있었네 ^ㅗ^...
  • string 이 기본적으로 immutable이라 특정 원소를 modify 할 수가 없네..

👉🏻 string to char array
(logic..)
return char array to string!

🔑 풀이 (Kotlin)

class Solution {
    fun solution(s: String): String {
        // make all alphabet to Uppercase
        val charArray = s.toLowerCase().toCharArray()
        // For keeping from out of index, start with 1
        for (index in 1 until charArray.size) {
            if (charArray[index].isLowerCase()) {
                with (charArray) {
                    // first alphabet of word is upper case
                    if (this[index-1] == ' ') this[index] = this[index].toUpperCase()
                }
            }
        }

        charArray[0] = charArray[0].toUpperCase()

        return String(charArray)
    }
}

🔑 풀이2 (C++)

#include <string>
#include <string.h>

using namespace std;

string solution(string s) {
    char str[s.length() + 1];
    // after strncpy null-terminate character should not be created
    strncpy(str, s.c_str(), sizeof(str));
    // so modify ending character to null-terminate character
    str[sizeof(str)] = '\0';
    
    // keeping from out of index starting '1'
    for (int index = 1; index < sizeof(str); index++) {
        str[index] = (str[index - 1] == ' ') ? toupper(str[index]) : tolower(str[index]);
    }
    // first character would be capital letter
    str[0] = toupper(str[0]);
    
    return string(str);
}

부록

문자열 뒤집기 코드

#include <string.h>
using namespace std;

string reverseWords(string S) {
    char str[S.length() + 1];
    const int length = sizeof(str);
    strncpy(str, S.c_str(), length);

    // after strncpy null-terminate character should not be created
    str[length] = '\0';

    for (int i = 0; i < length / 2 ; i++) {
        std::swap(str[i], str[length - i - 2]);
    }

    return string(str);
}


int main()
{
    cout << reverseWords("i.like.this.program.very.much") << endl;

    return 0;
}

🔗 Reference

profile
I'm still hungry

0개의 댓글