programing tip

문자열 스트림을 사용하여 쉼표로 구분 된 문자열을 분리하는 방법

itbloger 2020. 7. 18. 10:39
반응형

문자열 스트림을 사용하여 쉼표로 구분 된 문자열을 분리하는 방법


이 질문에는 이미 답변이 있습니다.

다음 코드가 있습니다.

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';
    }
}

참고 URL : https://stackoverflow.com/questions/11719538/how-to-use-stringstream-to-separate-comma-separated-strings

반응형