본문 바로가기
programming/c++

[c++]문자열 나누기(string tokenizer)

by 힐무새 2017. 12. 1.

C에서 문자열 나누기

  • C에서의 문자열 표현은 char 형태의 배열 또는 포인터로 구현된다. 즉 문자열을 표현하기 위한 primitive type이 존재하지 않는다. 
  • <string.h>에서 제공하는 strtok() 함수를 사용하여 문자열을 구분자를 기준으로 나눌 수 있다. 
  • 하지만 strtok는 문자 배열에만 사용이 가능하다는 단점이 있다. 즉 입력으로 고정된 길이의 문자 배열을 받아야 한다.

C++에서 문자열 나누기

  • 기본적으로 제공하는 STL 라이브러리는 없고, 직접 구현해서 활용해야 하는 듯하다. (정확하지는 않음.)
  1. string STL 이용
void Tokenize(const string & str, vector < string > & tokens,
  const string & delimiters = " ") {
  // 맨 첫 글자가 구분자인 경우 무시     
  string::size_type lastPos = str.find_first_not_of(delimiters, 0);
  // 구분자가 아닌 첫 글자를 찾는다     
  string::size_type pos = str.find_first_of(delimiters, lastPos);
  while (string::npos != pos || string::npos != lastPos) 
  {
    // token을 찾았으니 vector에 추가한다         
    tokens.push_back(str.substr(lastPos, pos - lastPos)); 
    // 구분자를 뛰어넘는다.  "not_of"에 주의하라         
    lastPos = str.find_first_not_of(delimiters, pos);
    // 다음 구분자가 아닌 글자를 찾는다         
    pos = str.find_first_of(delimiters, lastPos);

  }
}


 

2. stringstream 이용

#include <vector>
#include <string>
#include <sstream>

using namespace std;
int main() {
  string str("Split me by whitespaces");
  string buf; // 버퍼 string     
  stringstream ss(str); // string을 stream에 넣는다     
  vector < string > tokens; // word들을 넣을 vector     
  while (ss >> buf)
    tokens.push_back(buf);

}

 

 

참조 : https://wiki.kldp.org/HOWTO/html/C++Programming-HOWTO/standard-string.html

'programming > c++' 카테고리의 다른 글

[c++] 표준 입력  (0) 2017.12.02