2009-07-29 4 views
2

프로그램은 getline을 사용하여 문자열을 가져온 다음 해당 문자열을 공백으로 구분 된 하위 문자열에 저장하는 함수에 전달합니다. 나는 단지 루프로 문자를 읽음으로써 그것을했다.루프에서 문자열 인수 감지

그러나 지금 루프가 두 번째 문자열 인수에서 문자를 만나는 경우 문자열을 하위 문자열로 구분하는 두 번째 문자열 인수를 전달하려고합니다. 이것은 내가 지금까지 가지고있는 것이다. 의 [I]는 문자이고, w는 문자열이기 때문에

#include "std_lib_facilities.h" 

vector<string> split(const string& s, const string& w) // w is second argument 
{ 
    vector<string> words; 
    string altered; 
    for(int i = 0; i < s.length(); ++i) 
    { 
     altered+=s[i]; 
     if(i == (s.length()-1)) words.push_back(altered); 
     else if(s[i] == ' ') 
     { 
      words.push_back(altered); 
      altered = ""; 
     } 
    } 

    return words; 
} 



int main() 
{ 
    vector<string> words; 
    cout << "Enter words.\n"; 
    string word; 
    getline(cin,word); 
    words = split(word, "aeiou"); // this for example would make the letters a, e, i, o, 
            // and u divide the string 
    for(int i = 0; i < words.size(); ++i) 
      cout << words[i]; 
    cout << endl; 
    keep_window_open(); 
} 

그러나, 분명히 나는 ​​

if(s[i] == w) 

처럼 뭔가를 할 수 없습니다. 구현 한 루프 대신 문자열을 사용하여 문자열을 파싱해야합니까? 실제로 stringstream을 가지고 놀았지만 실제로 문자를 1 씩 읽어야하기 때문에 어떻게 도움이 될지 모르겠다.

P. split 인수는 문자열로 전달되어야하며 main()의 입력 형식은 getline이어야합니다.

+0

P.S.의 문자열 및 getline 사용 제한에 따라 숙제 일 수 있습니다. 그렇다면 질문에 "숙제"태그를 사용하십시오. –

+0

그렇지 않습니다. 책에서 스스로 배우기. – trikker

답변

6

std::string::find_first_of을 살펴보십시오. 이렇게하면 다른 문자열 객체의 다음 문자 위치에 대해 std :: string 객체에 쉽게 요청할 수 있습니다. 예를 들어

:

string foo = "This is foo"; 
cout << foo.find_first_of("aeiou"); // outputs 2, the index of the 'i' in 'This' 
cout << foo.find_first_of("aeiou", 3); // outputs 5, the index of the 'i' in 'is' 

편집 : 으악, 당신은이 목적을 위해 strtok를을 사용할 수 있습니다

+0

호출 오류에 대해 일치하는 기능을 얻지 못하고 문자열 헤더가 기능 헤더의 일부입니다. 기묘한. – trikker

+0

제대로 작동합니다. – trikker

+0

대부분의 찾기, 스왑 등 유형 함수는 아래에 있습니다. – jkeys

0

잘못된 링크. 이미 STL 라이브러리에 구현되어 있습니다.

 
#include 
#include 

int main() 
{ 
    char str[] ="- This, a sample string."; 
    char * pch; 
    printf ("Splitting string \"%s\" into tokens:\n",str); 
    pch = strtok (str," ,.-"); 
    while (pch != NULL) 
    { 
    printf ("%s\n",pch); 
    pch = strtok (NULL, " ,.-"); 
    } 
    return 0; 
} 
관련 문제