【C++實現python字符串函數庫】strip、lstrip、rstrip方法
這三個方法用於刪除字符串首尾處指定的字符,默認刪除空白符(包括'\n', '\r', '\t', ' ')。
s.strip(rm) 刪除s字符串中開頭、結尾處,位於 rm刪除序列的字符
s.lstrip(rm) 刪除s字符串中開頭處,位於 rm刪除序列的字符
s.rstrip(rm) 刪除s字符串中結尾處,位於 rm刪除序列的字符
示例:
>>> s=' abcdefg ' #默認情況下刪除空白符
>>> s.strip()
'abcdefg'
>>>
>>>#位於字符串首尾且在刪除序列中出現的字符全部被刪掉
>>> s = 'and looking down on tomorrow'
>>> s.strip('awon')
'd looking down on tomorr'
>>>
lsprit是只處理字符串的首部(左端),rsprit是只處理字符串的尾部(右端)。
C++實現
宏
#define LEFTSTRIP 0
#define RIGHTSTRIP 1
#define BOTHSTRIP 2
函數
內部調用函數do_strip
std::string do_strip(const std::string &str, int striptype, const std::string&chars)
{
std::string::size_type strlen = str.size();
std::string::size_type charslen = chars.size();
std::string::size_type i, j;
//默認情況下,去除空白符
if (0 == charslen)
{
i = 0;
//去掉左邊空白字符
if (striptype != RIGHTSTRIP)
{
while (i < strlen&&::isspace(str[i]))
{
i++;
}
}
j = strlen;
//去掉右邊空白字符
if (striptype != LEFTSTRIP)
{
j--;
while (j >= i&&::isspace(str[j]))
{
j--;
}
j++;
}
}
else
{
//把刪除序列轉為c字符串
const char*sep = chars.c_str();
i = 0;
if (striptype != RIGHTSTRIP)
{
//memchr函數:從sep指向的內存區域的前charslen個字節查找str[i]
while (i < strlen&&memchr(sep, str[i], charslen))
{
i++;
}
}
j = strlen;
if (striptype != LEFTSTRIP)
{
j--;
while (j >= i&&memchr(sep, str[j], charslen))
{
j--;
}
j++;
}
//如果無需要刪除的字符
if (0 == i&& j == strlen)
{
return str;
}
else
{
return str.substr(i, j - i);
}
}
}
strip函數
std::string strip( const std::string & str, const std::string & chars=" " )
{
return do_strip( str, BOTHSTRIP, chars );
}
lstrip函數
std::string lstrip( const std::string & str, const std::string & chars=" " )
{
return do_strip( str, LEFTSTRIP, chars );
}
rstrip函數
std::string rstrip( const std::string & str, const std::string & chars=" " )
{
return do_strip( str, RIGHTSTRIP, chars );
}
測試
int main()
{
string str = " abcdefg";
string result;
//不給定刪除序列時默認刪除空白字符串
result = strip(str);
cout << "默認刪除空白符:" << result << endl;
//指定刪除序列
result = strip(str, "gf");
cout << "指定刪除序列gf:" << result << endl;
str = "abcdefg";
string chars = "abfg";
//只刪除左邊
result = lstrip(str, chars);
cout << "刪除左邊" << result << endl;
//只刪除右邊
result = rstrip(str, chars);
cout << "刪除右邊" << result << endl;
system("pause");
return 0;
}