반응형
문자열 스트림을 사용하여 쉼표로 구분 된 문자열을 분리하는 방법
이 질문에는 이미 답변이 있습니다.
- 문자열의 단어를 어떻게 반복합니까? 답변 76 개
다음 코드가 있습니다.
std::string str = "abc def,ghi";
std::stringstream ss(str);
string token;
while (ss >> token)
{
printf("%s\n", token.c_str());
}
출력은 다음과 같습니다.
abc
def, ghi
따라서 stringstream::>>
연산자는 문자열을 공백으로 구분할 수 있지만 쉼표로 구분할 수 없습니다. 어쨌든 다음 결과를 얻을 수 있도록 위의 코드를 수정해야합니까?
입력 : "abc, def, ghi"
출력 :
abc
def
ghi
#include <iostream>
#include <sstream>
std::string input = "abc,def,ghi";
std::istringstream ss(input);
std::string token;
while(std::getline(ss, token, ',')) {
std::cout << token << '\n';
}
abc
데프
ghi
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
std::string input = "abc,def, ghi";
std::istringstream ss(input);
std::string token;
size_t pos=-1;
while(ss>>token) {
while ((pos=token.rfind(',')) != std::string::npos) {
token.erase(pos, 1);
}
std::cout << token << '\n';
}
}
반응형
'programing tip' 카테고리의 다른 글
힘내- "손상된"대화식 rebase를 고치는 방법? (0) | 2020.07.19 |
---|---|
MySQL에 이미지를 저장할 수 있습니까? (0) | 2020.07.19 |
PowerShell에서 경로 다시로드 (0) | 2020.07.18 |
dyld : 라이브러리가로드되지 않음 : PHP 관련 항목이있는 /usr/local/lib/libpng16.16.dylib (0) | 2020.07.18 |
요소 이름에 대한 사례 규칙? (0) | 2020.07.18 |