【C++实现python字符串函数库】strip、lstrip、rstrip方法

【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;
}

测试结果

posted @ 2015-09-11 22:48  melonstreet  阅读(6690)  评论(0编辑  收藏  举报