split函数用于擦除字符串中除字母和空格外的字符。然后将其拆分为单词并将其存储在矢量中。 像这样 输入:apple isnot4me 输出:“apple”“isnotme”
但phase.erase(phase.begin() + index);
似乎不起作用。
这是我在C ++中的程序
#include <iostream>
#include <string>
#include <vector>
using namespace std;
const string ALPHABET("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ");
void split(vector<string> &words, const string &phase)
{
int pos = 0, size = 0, index = 0;
//erace the chracters except for letters and spaces
while((index = phase.find_first_not_of(ALPHABET, pos)) != string::npos)
{
phase.erase(phase.begin() + index);
pos = index;
}
pos = 0, size = 0, index = 0; //initialize again
while((index = phase.find_first_of(" ", pos)) != string::npos)
{
size = index - pos;
words.push_back(phase.substr(pos, size));
pos = index + 1;
}
//add the last word(if exists) to the vector words
size = phase.length() - pos;
words.push_back(phase.substr(pos, size));
}
int main()
{
vector<string> words;
string str;
cin >> str;
split(words, str);
int size = words.size();
for(int i = 0; i < size; i++)
{
cout << "\"" << words[i] << "\"" << ' ';
}
cout << endl;
return 0;
}
然而,当我在另一个程序中独立尝试str.erase(str.begin()+ index)时, 像这样
#include <iostream>
#include <vector>
using namespace std;
int main()
{
string str("Hello world!");
int index = str.find_first_of(" ", 0);
str.erase(str.begin() + index);
cout << str << endl;
return 0;
}
它有效!
答案 0 :(得分:2)
您将阶段作为 const 字符串传递:
void split(vector<string> &words, const string &phase)
令人惊讶的是你可以编译,因为擦除不是常量...(不应该是)