2009-07-29 4 views
2

プログラムはgetl​​ineを使用して文字列を受け取り、その文字列を空白で区切られた部分文字列に格納する関数に渡します。私はループで文字を読むだけでそれをやった。ループ内の文字列引数の検出

しかし、ループが2番目の文字列引数に文字を検出すると、文字列を部分文字列に分割する2番目の文字列引数を渡そうとしています。これは私がこれまで持っていたものです。 S [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) 

ような何かをすることはできません。実装したループではなく文字列を解析する必要がありますか?私は実際にストリングストリームで遊んでいましたが、どのように役立つか分かりません。何故なら、私は文字1を1で読む必要があるからです。

P.S. splitへの引数は文字列として渡す必要があり、main()の入力フォームはgetl​​ineでなければなりません。

+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' 

編集:おっと、間違ってリンク

+0

呼び出しエラーに対してno matching関数を取得し、文字列ヘッダーはfacilityヘッダーの一部です。奇妙な。 – trikker

+0

それは働いた。 – trikker

+0

find、swapなどの型関数のほとんどは、にあります。 – jkeys

0

あなたは、この目的のためにはstrtokを使用することができます。すでに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; 
} 
関連する問題