문제풀이: 문자열 스트림 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;
}
'코딩테스트' 카테고리의 다른 글
프로그래머스_1단계_음양 더하기_C++ (0) | 2024.04.11 |
---|---|
프로그래머스_0단계_ad 제거하기_C++ (0) | 2024.04.11 |
프로그래머스_0단계_숨어있는 숫자의 덧셈 (1)C++ (0) | 2024.04.11 |
프로그래머스_0단계_문자열 정렬하기 (1)C++ (0) | 2024.04.11 |
프로그래머스_0단계_뒤에서 5등까지C++ (0) | 2024.04.11 |