用C++實現split/startswith/endswith/trim
阿新 • • 發佈:2019-01-28
一.split函式
1.python演示
2.C++函式原型
vector<string> split(const string& srcstr, const string& delimeter = ";");//split the string by delimeter
3.實現思路
用delimeter分割符將字串srcstr分割開,結果儲存到向量中,預設的分割符為”;”。思路是,
(1)find_first_not_of(delimeter)即為開始切割的位置pos_begin
(2)隨後find(delimeter),找到第一個分隔符的位置dlm_pos
(3)那麼加在dlm_pos和pos_begin中間的字串為第一個結果,儲存在vector中
(4)以此迴圈,更新pos_begin和dlm_pos,直到pos_begin超出srcstr的範圍,即到達string::npos
4.原始碼展示
//strutils.cpp
vector<string> split(const string& srcstr, const string& delimeter)
{
vector<string> ret(0);//use ret save the spilted reault
if(srcstr.empty()) //judge the arguments
{
return ret;
}
string::size_type pos_begin = srcstr.find_first_not_of(delimeter);//find first element of srcstr
string::size_type dlm_pos;//the delimeter postion
string temp; //use third-party temp to save splited element
while(pos_begin != string::npos)//if not a next of end, continue spliting
{
dlm_pos = srcstr.find(delimeter, pos_begin);//find the delimeter symbol
if(dlm_pos != string ::npos)
{
temp = srcstr.substr(pos_begin, dlm_pos - pos_begin);
pos_begin = dlm_pos + delimeter.length();
}
else
{
temp = srcstr.substr(pos_begin);
pos_begin = dlm_pos;
}
if(!temp.empty())
ret.push_back(temp);
}
return ret;
}
二.startswith函式
1.python展示
2.C++函式原型
bool startswith(const std::string& str, const std::string& start)
3.實現思路
str截取出前len個字元與start比較(len為start字串的長度)
4.程式碼展示
//strutils.cpp
bool startswith(const std::string& str, const std::string& start)
{
int srclen = str.size();
int startlen = start.size();
if(srclen >= startlen)
{
string temp = str.substr(0, startlen);
if(temp == start)
return true;
}
return false;
}
三.endswith函式
1.python展示
2.C++函式原型
bool endswith(const std::string& str, const std::string& end)
3.實現思路
str截取出最後len個字元與start比較(len為start字串的長度)
4.程式碼展示
bool endswith(const std::string& str, const std::string& end)
{
int srclen = str.size();
int endlen = end.size();
if(srclen >= endlen)
{
string temp = str.substr(srclen - endlen, endlen);
if(temp == end)
return true;
}
return false;
}
四.trim函式
1.python演示
注:python中strip是trim掉字串兩邊的空格。
lstrip, trim掉左邊的空格
rstrip, trim掉右邊的空格
2.C++函式原型
string trim(const std::string& str)
3.實現思路
查詢第一個不是空格或者製表符的位置pos_begin,查詢最後一個不是空格和製表符的位置pos_end,那麼夾在兩者之間的即為trim掉字串兩邊空格和\t的新字串
4.程式碼展示
string trim(const std::string& str)
{
string ret;
//find the first position of not start with space or '\t'
string::size_type pos_begin = str.find_first_not_of(" \t");
if(pos_begin == string::npos)
return str;
//find the last position of end with space or '\t'
string::size_type pos_end = str.find_last_not_of(" \t");
if(pos_end == string::npos)
return str;
ret = str.substr(pos_begin, pos_end-pos_begin);
return ret;
}