공백으로 구분하기 2

Subin·2024년 8월 26일

Algorithm

목록 보기
23/69

[내 풀이]

#include <string>
#include <vector>

using namespace std;

vector<string> solution(string my_string) {
    vector<string> answer;
    string res;
    // res도 값이 없고 문자열이 공백이면 다음 인덱스로 넘겨버리기, 아니면 res에 붙이고 공백일 때 answer에 추가
    for(int i=0; i<my_string.length(); i++)
    {
        if(my_string[i] == ' ' && res == "")
        {
            continue;
        }
        if(my_string[i] != ' ')
            res += my_string[i];
        if(my_string[i] == ' ' && res != "")
        {
            answer.push_back(res);
            res = "";
        }
    }
    if(res != "") // 넣을 res가 있다면
        answer.push_back(res);

    return answer;
}

[다른 사람 풀이]

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

using namespace std;

vector<string> solution(string my_string) {
    vector<string> answer;

    string str;
    stringstream ss;
    ss.str(my_string);
    while(ss >> str)
    {
        answer.emplace_back(str);
    }

    return answer;
}

    string str;

문자열 변수, 나중에 stringstream으로부터 단어를 하나씩 받아서 저장하는 데 사용됨

    stringstream ss;

stringstream 객체 ss를 선언, 문자열을 단어로 분리하기 위해 사용됨

    ss.str(my_string);

ssmy_string을 초기화. ssmy_string의 내용을 담고 있으며, 이 내용을 기반으로 문자열을 파싱할 수 있음

    while(ss >> str)

while 루프는 ss로부터 공백을 기준으로 하나씩 단어를 추출하여 str에 저장, 스트림에서 더 이상 읽을 데이터가 없을 때까지 반복됨


++

만약 ss >> str1 >> str2 하면 공백을 기준으로 str1과 str2로 구분

profile
성장하며 꿈꾸는 삶을 살아가고 있는 대학생입니다😊

0개의 댓글