程序使用getline獲取一個字符串,然後將該字符串傳遞給一個函數,該字符串將字符串存儲到由空格分隔的子字符串中。我只是通過循環閱讀字符來做到這一點。檢測循環中的字符串參數
但是,現在我試圖傳遞第二個字符串參數,如果循環遇到第二個字符串參數中的字符,則將字符串分隔成子字符串。這是我迄今爲止所擁有的。
#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)
,因爲S [i]爲一個char和w是一個字符串。我是否需要使用stringstream來解析字符串,而不是我實現的循環?我實際上玩過stringstream,但並不真正知道它可以提供什麼幫助,因爲無論哪種方式,我必須通過1讀取字符1.
P.S. split的參數必須作爲字符串傳遞,main()中的輸入表單必須是getline。
看來,基於在你的P.S.中使用字符串和getline的限制,這可能是作業。如果是這樣,請在您的問題上使用「作業」標籤。 – 2009-07-29 20:48:37
不是。從書中自學。 – trikker 2009-07-29 20:50:14