2014-05-09 3 views
-3

로 C++에서 문자열을 tokenise 어떻게 내가 가진 : 사용자가 inputed됩니다내가 문자열

string content; 

. 예를 들어

는 :

content = "I am new to this site". 

내가이 캐릭터를 통해 내가 단어를 처리하는 기능을 실행하고자하는 문장의 각 단어에 대한 루프합니다. 이 같은

무엇인가 : 어떤 도움이 많이 주시면 감사하겠습니다

for(int i = 0; i < stringSize; i++){ 
//remove a word from the string 
process(word); 
} 

. 고마워요

+0

http://www.cplusplus.com/reference/cstring/ strtok/ –

+0

또한 : [C++에서 문자열을 분할하는 방법] (http://stackoverflow.com/questions/236129/how-to-split-a-string-in-c?rq=1) – MatthiasB

답변

1

공백 (공백, 탭, 줄 바꿈 등)에 std::string을 분할 : 여기

int main() 
{ 
    std::string content = "I am new to this site"; 
    std::vector<std::string> tokens = tokenize(content); 
    std::vector<std::string>::iterator iter = tokens.begin(); 
    for (; iter != tokens.end(); ++iter) 
    { 
     std::cout << *iter << std::endl; 
    } 
} 

출력의 스 니펫은 content에있는 각 단어를 각 행에 한 단어 씩 인쇄합니다.

참고 :

+0

고맙습니다. 이게 내가 필요한거야. – fadim

0

다음은 문자열을 받아 토큰 목록을 반환하는 함수입니다.

std::vector<std::string> tokenize(std::string const& content) 
{ 
    std::vector<std::string> tokens; 
    size_t iter = 0; 
    size_t next = 0; 
    while ((next = content.find(" ", iter)) != std::string::npos) 
    { 
     tokens.push_back(content.substr(iter, next-iter)); 
     iter = ++next; 
    } 
    tokens.push_back(content.substr(iter)); 
    return tokens; 
} 

다음은 테스트를 위해 사용한 주요 기능입니다.

std::string content = "I am new to this site"; 
std::vector<std::string> words; // Will contain each word of the `content` string 

std::istringstream iss(content); 
std::copy(std::istream_iterator<std::string>(iss), 
      std::istream_iterator<std::string>(), 
      std::back_inserter(words)); 

for (const std::string& w : words) 
    std::cout << w << '\n'; 

위의 코드 : 다음 사용할 수있는 경우

 
I 
am 
new 
to 
this 
site 
0

여기에 재미를위한 부스트 솔루션이 있습니다. 당신이 원하지 않는 문자열을 제거하고 연속 된 구분자를 하나로 처리합니다. 당신이 C++ (11)이없는 경우, 자신의 함수에 대한 포인터로 람다 교체 :

#include <boost/algorithm/string/find_iterator.hpp> 
#include <boost/algorithm/string/split.hpp> 
#include <boost/algorithm/string/classification.hpp> 
#include <boost/algorithm/string.hpp> 
using namespace std; 

int main(int argc, char** argv) 
{ 
    const string delim{' '}; 
    vector<string> splitVec; 
    string inStr = "keep all this but remove THAT if you see it"; 
    boost::split(splitVec, inStr, boost::algorithm::is_any_of(&delim[0]), boost::token_compress_on); 
    copy_if(splitVec.begin(),splitVec.end(), ostream_iterator<string>(cout," "), [](const string& argStr) -> bool { return(argStr != "THAT"); }); 
} 

가 제공합니다 :

keep all this but remove if you see it