2010-08-10 6 views
1

가능한 중복 :
How to split a string?발견 하위 문자열 C++

안녕,

나는 문자열 "1,0,1"는, 내가 얻을 수있는 방법 문자열 분리 말을해야 쉼표 연산자로.

+0

http://stackoverflow.com/questions/599989/is-there-a-built-in-way-to-split-strings-in-c는 더 나은 복제본입니다. 첫 번째 질문은 공백에만 분할하는 방법을 구체적으로 묻습니다. – jalf

답변

-1

알고리즘을 검색하려면 또는 토큰 크기 문자열을 검색하십시오. 사소한 일이야.

또한 문서를 확인하고 사용 가능한 도구를 사용할 수 있습니다 http://www.cplusplus.com/reference/string/string/

간단한 구현 될 수있다 :

void tokenize(const string & text, vector<string> & tokens, char delim) 
{ 
    size_t length = text.size(); 
    string token = ""; 

    for(size_t i=0;i<length;i++) 
    { 
     if(text[i] != delim) 
     { 
     token += text[i]; 
     } 
     else 
     { 
     if(token.size() > 0) 
     { 
      tokens.push_back(token); 
     } 
     token = ""; 
     } 
    } 
    tokens.push_back(token); 
} 
2

C++가 정확히이 일을 위해 기능이 내장되어 있지 않습니다. 그러나 std::string::find_first_of 멤버 함수 또는 비 멤버 std::find을 사용하여 구현할 수 있습니다. 물론이 국경 많은 경우는 처리 할 수 ​​있으며,이 구현은 정확하게 당신이 원하는 일을하지 않을 수도 있지만, 그것은 당신에게 출발점을 제공한다

#include <string> 
#include <vector> 
#include <algorithm> 


// given a string str, split it on every occurrence of the character delim 
std::vector<std::string> tokenize(std::string str, char delim) { 
    // store the results in a vector of strings 
    std::vector<std::string> tokens; 

    std::string::iterator end = str.end(); 
    std::string::iterator left = str.begin(); 
    for (;;) { 
     // find the next occurrence of the delimiter 
     std::string::iterator right = std::find(left, end, delim); 
     // create a string from the end of last one up until the one we just foun 
     tokens.push_back(std::string(left, right)); 
     // if we reached the end of the string, exit the loop 
     if (right == end) { break; } 
     // otherwise, start the next iteration just past the delimiter we just found 
     left = right + 1; 
    } 
    return tokens; 
} 

// test program 
int main() { 
    std::string str = "foo, bar, baz"; 
    std::string str2 = "foo, bar, baz,"; 
    std::string str3 = "foo"; 
    std::string str4 = ""; 
    std::string str5 = ","; 

    std::vector<std::string> tokens = tokenize(str, ','); 
    std::vector<std::string> tokens2 = tokenize(str2, ','); 
    std::vector<std::string> tokens3 = tokenize(str3, ','); 
    std::vector<std::string> tokens4 = tokenize(str4, ','); 
    std::vector<std::string> tokens5 = tokenize(str5, ','); 
} 

:

다음은 후자를 사용하는 예제입니다.

+0

벡터를 반환하는 것은 좋은 생각이 아닙니다. 참조로 전달 된 함수 인수가 더 좋을 것입니다. –

+0

'find'도'std :: string'의 멤버 함수로 사용할 수 있습니다. – Scharron

+0

@ 숙녀 : 왜? 모든 주요 컴파일러는 낮은 수준의 최적화에서도 NRVO를 구현합니다. – jalf

0

이렇게하는 또 다른 방법은 strtok을 사용하는 것입니다. 이것은 오래된 c 방법이지만 여전히 문제에 적용됩니다.

using <vector> 
using <string> 

char* token, line[512]; 
std::string tokenStr; 
std::string lineStr = "0, 1, 2"; 
std::vector<std::string> commaSplit; 
strcpy (line, lineStr.c_str()); 

//Remove spaces and find the first instance of ',' 
token = strtok(line, " ,"); 
while(token != NULL) 
{ 
    //Copy the token to a string 
    tokenStr = token; 

    //Add the token to the vector 
    commaSplit.push_back(token); 

    //Find next instance of the , 
    token = strtok(NULL, " ,"); 
}