유용한 정보

string split 하는법 C++ | sstream 사용법 C++ | find함수 substr함수

cosmohoo 2021. 12. 2. 21:56
반응형
#include <string>
#include <iostream>
#include <sstream>
using namespace std;


int main()
{
    stringstream ss;
    string tmp;
    ss.str("Hello new World of Sstream!!!");
    ss << "Start" <<".......";
    while(ss >> tmp) cout << tmp << " ";
    
    cout <<'\n';
    
    stringstream s;
    string tmp2="123 456";
    s.str(tmp2);
    int number;
    while(s >> number) cout << number << " ";
}

 C++ 에는 JAVA와 PYTHON과는 달리 split함수가 없습니다. 해당 함수를 찾는 방법에는 두 가지 방법이 있습니다. 

1. sstream 사용
2. find함수 + substr 함수 사용

 

1. sstream 사용 

 

- 우선 <sstream> 헤더를 참조해야 합니다. 

- sstream 객체를 생성해준 후, str함수안에 string객체를 집어넣습니다. 

- 그 이후, 자유롭게 사용합니다. 

int main()
{
    stringstream ss;
    string tmp;
    ss.str("Hello new World of Sstream!!!");
    ss << "Start" <<".......";
    while(ss >> tmp) cout << tmp << " ";
    
    cout <<'\n';
    
    stringstream s;
    string tmp2="123 456";
    s.str(tmp2);
    int number;
    while(s >> number) cout << number << " ";
    
    cout << '\n';
    
    cout << typeid(number).name()<<'\n'; // number형 자료형 확인
}

=> stringstream ss의 경우 >>를 하면 앞에서부터 해당 문자열만큼 대치되는 것을 알 수 있습니다. 

=> 또한 띄어쓰기를 확인하여 나눠서 출력되는 것을 볼 수 있습니다. 

=> string객체 안에 숫자가 있는 경우 int형으로 받아줘야 하는 제대로 된 값이 출력됩니다. 

=> 숫자가 있는 경우 string으로 받을 경우 제대로 된 값이 출력되지 않습니다. 

 

정상출력화면

 

sstream안에 숫자가 있을 때 string으로 받은 경우&amp;nbsp;

 

-이를 이용해 split 함수를 만들 수 있습니다. 

 

#include <string>
#include <vector>
#include <iostream>
#include <map>
#include <sstream>
#include <typeinfo>
using namespace std;

vector<string> split(string sentence, char Separator)
{
    vector<string> answer;
    stringstream ss(sentence);
    string tmp;
 
    while (getline(ss, tmp, Separator)) {
        answer.push_back(tmp);
    }
    return answer;
}

int main(){
    string s = "Hello Sstream World";
    vector<string> answer = split(s, ' ');
   
    for(auto tmp : answer)cout <<tmp <<" ";
    cout<<'\n';
}

 

 

출력화면

 

 

https://modoocode.com/236

 

C++ 레퍼런스 - string 의 getline 함수

 

modoocode.com

*getline함수의 사용법은 위에서 확인 가능합니다. 

 

 

 

 

2. find함수 + substr함수 사용

 

#include <string>
#include <vector>
#include <iostream>
#include <map>
#include <sstream>
#include <typeinfo>
using namespace std;

int main(){
    string tmp = "welcome to splitWorld!!! ";
    int prev = 0; //이전 위치
    int cur; //현재위치
    cur = tmp.find(' ');
    while (cur != string::npos)
    {
        string substring = tmp.substr(prev, cur - prev); //첫인자에서부터 두번째 인자의 크기만큼까지를 반환하는 함수이다. => substr
        cout << substring << " ";
        prev = cur + 1;
        cur = tmp.find(' ',prev); //prev지점부터 탐색을 시작한다.
    }
    //남아있는 문자열 출력
    cout << tmp.substr(prev, cur - prev);
    return 0;
    
}

출력화면&amp;nbsp;

 

=> while문 들어갈때의 prev와 cur 변수의 값입니다. 

=> find(첫번째 인자, 두 번째 인자) : 두 번째 인자에서부터 첫 번째 인자가 있는 값의 INDEX를 반환합니다. 대신, 해당 값이 없는 경우에는 string::npos를 반환하게 됩니다. (이를 기억하지 못하면 말짱 황.....) 

=> 맨 마지막부분에는 저희가 원하는 인자가 없으므로 값을 찾지 못하고 출력할 수 있으므로 while문 이후에 출력문을 하나 더 작성해주어야 합니다. 

 

 

 

 


문자열을 split하는 경우는 간혹 코딩 테스트에서 요구하는 경우가 있습니다.

구글링으로 검색해서 해낼 수 있으면 문제가 없다고 생각하지만, 코딩 테스트에서는 구글링을 허용하지 않으니 시간이 날 때 외우는 편이 좋아 보입니다. 

특히 stringstream의 경우, 손에 익히는 과정이 필요합니다. 

 

 

 

반응형