Algorithm

[C++] string 자르는 2가지 방법(feat. istringstream 이용하기, substr 이용하기)

용성군 2021. 12. 31. 01:27
728x90
반응형

C++을 사용하다보면 문자열을 자를 때, python과 Java와 다르게 .split()이라는 내장함수가 없기 때문에 다른방법으로 만들어서 사용해야한다. C++에서 간단하게 문자열을 자르는 방법 두가지를 작성하려고 한다. 


stringstream을 이용해서 자르는 방법

 

앞선 글에서 기본적인 stringstream에 대해서 알아보았다. 과연 istringstream과 stringstream과의 차이점은 무엇일까?

2021.12.31 - [Algorithm] - [C++] stringstream 사용법(feat. stream과 버퍼란 무엇인가?)

 

[C++] stringstream 사용법(feat. stream과 버퍼란 무엇인가?)

C++에서 문자열을 공백과 \n 을 기준으로 int형 string형 float형 등 다양하게 자를 수 있도록 하는 stringstream이 존재한다. 이것을 어떻게 쓰는지 알아보도록 하자. stringstream을 설명하기 전에 stream은

roadtosuccess.tistory.com

두가지 모두 문자열을 다룰 때 유용하게 사용 가능한 Class이다. 

1. stringstream

    - 문자열에서 내가 원하는 자료형의 데이터를 추출할 때 사용한다.

2. istringstream

    - 문자열 포맷을 parsing 할 때 사용합니다.

 

istringstream은 문자열 포맷을 parsing할 때, getline과 같이 사용하면 원하는 문자를 기준으로 자를 수 있다. 

 

istringstream 과 getline 함수를 사용(공백을 기준으로)

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main()
{
    string str = "Enter id1234 Muzi";//다음과 같은 string이 있다고하자.
    istringstream ss(str);//istringstream ss 변수에 string 변수 as로 초기화한다.
    string buff;
    while (getline(ss, buff, ' '))//ss stream 변수에서 ' '(공백)까지 입력으로 받아들인다.
    {
        // getline으로 읽어들인 값을 buff에 저장해 출력한다.
        cout << buff <<endl;
    }
    return 0;
}
//출력
//Enter
//id1234
//Muzi

istringstream 과 getline 함수를 사용(,을 기준으로)

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main()
{
    string str = "Enter,id1234,Muzi";//다음과 같은 string이 있다고하자.
    istringstream ss(str);//istringstream ss변수에 string 변수 as로 초기화한다.(ss는 str의 문자열을 가진다.)
    string buff;
    while (getline(ss, buff, ','))//ss에서 ','(쉽표)까지 입력으로 받아들인다.
    {
        // getline으로 읽어들인 값을 buff에 저장해 출력한다.
        cout << buff <<endl;
    }
    return 0;
}
//출력
//Enter
//id1234
//Muzi
반응형

string find와 substr을 이용하여 자르기

 

밑의 주석을 따라가면 이해할 수 있을 것이다. find에 대한 설명은 이전 글을 참조하면 좋을 것 같아 링크로 달아 놓는다. 

2021.12.30 - [Algorithm] - [알고리즘] C++ string::find() 사용법

 

[알고리즘] C++ string::find() 사용법

알고리즘 풀 때, 문자열에 대한 문제가 나오는 경우가 많다. 이때 마다 인터넷을 검색해서 풀 수 없으니 정리를 해보고자 한다. C++ string 변수에서 특정 문자열을 찾을 때, std::string의 find() 함수를

roadtosuccess.tistory.com

#include<iostream>
#include<string>
#include<sstream>
#include<vector>
 
using namespace std;
 
int main()
{
    string s = "Enter id1234 Muzi";
    size_t index = 0;
    size_t current;
    current = s.find(' '); //find 함수는 0번 위치부터 문자열을 찾지 못할 경우 npos를 반환
   
    while (current != string::npos)
    {
        
        string sub = s.substr(index, current - index);// 첫 인자의 위치(index)부터 두번째 인자 길이(current - index)만큼 string을 sub에 할당
        cout << sub << endl;
        index = current + 1;
        //index 부터 ' '(공백)이 나오는 위치를 찾는다.
        current = s.find(' ',index);
    }
  
    cout << s.substr(index, current - index);  //마지막 문자열 출력
    return 0;
}
728x90
반응형