對一個字符串根據某個字符進行分割也是在實戰中經常遇到的問題,也是面試中經常會被人提及的。
如果你是個C Sharp程序員,你會知曉string.split函數,有下面這些重載:
1) public string[] Split(params char[] separator)
2) public string[] Split(char[] separator, int count)
3) public string[] Split(char[] separator, StringSplitOptions options)
4) public string[] Split(string[] separator, StringSplitOptions options)
5) public string[] Split(char[] separator, int count, StringSplitOptions options)
6) public string[] Split(string[] separator, int count, StringSplitOptions options)
如果你是個PHP程序員,你也會使用explode方法。
但是如果你是C++程序員,或是進行C++開發,那麼這裡的string就沒有現成的分割方法。我們需要自行實現。
const vector explode(const string& s, const char& c)
{
string buff{""};
vector v;
for(auto n:s)
{
if(n != c) buff+=n;
elseif(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 v{explode(str, ' ')};
for(auto n:v) cout << n << endl;
return 0;
}
//輸出如下:
the
quick
brown
fox
...
下面是另一種形式:
int split(const string& str, vector& ret_, string sep = ",")
{
if (str.empty())
{
return 0;
}
string tmp;
string::size_type pos_begin = str.find_first_not_of(sep);
string::size_type comma_pos = 0;
while (pos_begin != string::npos)
{
comma_pos = str.find(sep, pos_begin);
if (comma_pos != string::npos)
{
tmp = str.substr(pos_begin, comma_pos - pos_begin);
pos_begin = comma_pos + sep.length();
}
else
{
tmp = str.substr(pos_begin);
pos_begin = comma_pos;
}
if (!tmp.empty())
{
ret_.push_back(tmp);
tmp.clear();
}
}
return 0;
}
=============================================================
其他語言的string也有replace的方法,那麼再c++中我們也可以自己實現這個方法:
string replace(const string& str, const string& src, const string& dest)
{
string ret;
string::size_type pos_begin = 0;
string::size_type pos = str.find(src);
while (pos != string::npos)
{
cout <<"replacexxx:" << pos_begin <<" " << pos <<"\n";
ret.append(str.data() + pos_begin, pos - pos_begin);
ret += dest;
pos_begin = pos + 1;
pos = str.find(src, pos_begin);
}
if (pos_begin < str.length())
{
ret.append(str.begin() + pos_begin, str.end());
}
return ret;
}
================================================================
最後介紹一個C中的函數,用於截取字符串:
原型:extern char *strtok(char *s, char *delim);
#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;
}
輸出:
Splitting string “- This, a sample string.” into tokens:
This
a
sample
string