程序使用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();
}
Run Code Online (Sandbox Code Playgroud)
但是,显然我做不了类似的事情
if(s[i] == w)
Run Code Online (Sandbox Code Playgroud)
因为s [i]是char而w是字符串.我是否需要使用字符串流来解析字符串而不是我实现的循环?我实际上玩过stringstream,但实际上并不知道它是如何帮助的,因为无论哪种方式我都必须逐个读取字符.
PS split的参数必须作为字符串传递,main()中的输入形式必须是getline.
看看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'
Run Code Online (Sandbox Code Playgroud)
编辑:哎呀,错误的链接