C++/std:string 토크나이즈

  1. vector<string> tokenize(const string& str, const string& delimiters)
  2. {
  3.     vector<string> tokens;
  4.     string::size_type lastPos = 0, pos = 0;  
  5.     int count = 0;
  6.     if(str.length()<1)  return tokens;
  7.     // skip delimiters at beginning.  
  8.     lastPos = str.find_first_not_of(delimiters, 0);
  9.       
  10.     if((str.substr(0, lastPos-pos).length()) > 0)
  11.     {   
  12.         count = str.substr(0, lastPos-pos).length();    
  13.         for(int i=0; i < count; i++)     
  14.             tokens.push_back("");
  15.         if(string::npos == lastPos)
  16.             tokens.push_back("");
  17.     }
  18.     // find first "non-delimiter".
  19.     pos = str.find_first_of(delimiters, lastPos);
  20.     while (string::npos != pos || string::npos != lastPos)
  21.     {               
  22.         // found a token, add it to the vector.
  23.         tokens.push_back( str.substr(lastPos, pos - lastPos));
  24.                 
  25.         // skip delimiters.  Note the "not_of"
  26.         lastPos = str.find_first_not_of(delimiters, pos);               
  27.         
  28.         if((string::npos != pos) && (str.substr(pos, lastPos-pos).length() > 1))         
  29.         {
  30.             count = str.substr(pos, lastPos-pos).length();
  31.             for(int i=0; i < count; i++)
  32.                 tokens.push_back("");
  33.         }
  34.         
  35.         pos = str.find_first_of(delimiters, lastPos);
  36.     }
  37.     return tokens;
  38. }
  39. ...
  40. string delimiters(" ");
  41. // 공백 구분자로 토크나이즈            
  42. vector<string> tokens = tokenize(src, delimiters);    

명차 한자리에 랄프 로렌 자동차 컬렉션
↓
vector<string>
"명차" "한자리에" "랄프" "자동차" "컬렉션" 

이 글에는 0 개의 댓글이 있습니다.