Foollowing is the definition of explode(using C++ 11)
#include
#include
#include
using namespace std;
const vector<string> explode(const string& str, const char& c)
{
string buff{""};
vector<string> v;
for(auto n:str)
{
if(n != c) buff +=n;
else {
if(n ==c && buff != "")
{
v.push_back(buff);
buff = "";
}
}
}
if(buff != "") v.push_back(buff);
}
int main(){
string str{"the quick brown fox jumps over the lazy dog"};
// error : nvalid conversion from 'const char*' to 'char'
vector<string> vec {explode(str," ")};
// for(auto n :vec) std::cout << n <
return 0;
}
上面的代码编译器会报如下错误
error : nvalid conversion from 'const char’ to ‘char’*
下面我分析下:编译器报上述错误的原因
我们可以将函数 explode的第二个 argument参数修改为 指针 。
即函数原型
const vector explode(const string& str, const char c*){}
#include
#include
#include
using namespace std;
const vector<string> explode(const string& str, const char* c)
{
string buff{""};
vector<string> v;
for(auto n:str)
{
if(n !=*c) buff +=n;
else {
if(n ==*c && buff != "")
{
v.push_back(buff);
buff = "";
}
}
}
if(buff != "") v.push_back(buff);
return v;
}
int main(){
string str{"the quick brown fox jumps over the lazy dog"};
vector<string> v = explode(str," ");
vector<string> vec {v};
for(auto n :vec) std::cout << n <<std:: endl;
return 0;
}
输出:
the
quick
brown
fox
jumps
over
the
lazy
dog