[프로그래머스/C++] 이상한 문자 만들기

꿈별·2024년 1월 18일
0

문제풀이

목록 보기
39/52

문제


풀이

오답

이 코드는 문제의 테스트 케이스는 통과하지만 제출하면 일부 실패가 뜬다.
일단 다른 풀이로 답을 맞추긴 했지만 왜 틀린 건지 생각해 봤다.

#include <string>
#include <vector>
#include <sstream>

using namespace std;

string solution(string s) {
    string answer = "", token;
    vector<string> cut;
    stringstream str(s);
    
    while (str >> token) {
        cut.push_back(token);
    }

    for (int i = 0; i < cut.size(); i++)
    {
        for (int j = 0; j < cut[i].size(); j++)
        {
            if (0 == j % 2) // 0, 짝수 : 대문자
            {
                cut[i][j] = toupper(cut[i][j]);
            }
            else // 홀수 : 소문자
            {
                cut[i][j] = tolower(cut[i][j]);
            }
        }
        answer += cut[i];
        if (cut.size()-1 != i)
            answer += ' ';
    }
    return answer;
}

  • 내가 빠뜨린 예외
  1. 문자열이 공백문자로 시작하는 경우
    : 공백문자를 단어 사이에 넣으려고 한 게 오류



  1. 공백문자가 2개 이상인 경우
    : 공백문자를 단어 사이에 한 개씩 넣으려고 한 게 오류
    문제에 하나 이상의 공백문자라고 써져 있다. 문제를 잘 읽자..



정답

#include <string>
#include <vector>
#include <iostream>

using namespace std;

string solution(string s) {
    int idx = 0;

    for (int i = 0; i < s.length(); i++)
    {
        // 공백 문자가 나오면 각 단어의 인덱스 초기화
        if (' ' == s[i])
        {
            idx = 0;
            continue;
        }
        // 인덱스가 0,짝수 : 대문자 , 홀수 : 소문자 변환
        s[i] = (0 == idx % 2) ? toupper(s[i]) : tolower(s[i]);
        idx++;
    }
    return s;
}

문자열 파싱

공백 기준으로 자르기
https://velog.io/@bys096/C-%EB%AC%B8%EC%9E%90%EC%97%B4-%ED%8C%8C%EC%8B%B1-stringstream-istringstream-ostringstream


대소문자 변환

  • 헤더
// C
#include <ctype.h>
// C++
#include <cctype>
  • tolower()
    대->소 / 소->대
  • toupper()
    소->대 / 대->대

0개의 댓글