본문 바로가기

코딩테스트

프로그래머스_0단계_공백으로 구분하기 1C++

 

문제풀이: 문자열 스트림 istringstream 

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

using namespace std;

vector<string> solution(string my_string) {
    vector<string> answer;
    
    // 문자열 스트림 생성
    istringstream iss(my_string);
    string word;

    // 공백을 기준으로 문자열을 분리하여 각 단어를 추출하고 배열에 담음
    while (iss >> word) {
        answer.push_back(word);
    }

    return answer;
}

 

만약 문자열 스트림을 사용하지 않았을때의 코드

#include <string>
#include <vector>

using namespace std;

vector<string> solution(string my_string) {
    vector<string> answer;
    
    // 문자열에서 공백을 찾음
    size_t pos = my_string.find(' ');

    // 공백을 찾을 때까지 반복
    while (pos != string::npos) {
        // 공백 이전까지의 문자열을 추출하여 벡터에 추가
        answer.push_back(my_string.substr(0, pos));
        
        // 다음 공백을 찾기 위해 문자열을 갱신
        my_string = my_string.substr(pos + 1);
        
        // 갱신된 문자열에서 다음 공백을 찾음
        pos = my_string.find(' ');
    }
    
    // 마지막 단어를 벡터에 추가
    answer.push_back(my_string);

    return answer;
}