C++去掉字符串前后的多余空格

C++中std::string 没有可以直接去掉字符串前后多余空格的接口,所以自己实现了一个。

借鉴Qt中QString的trimmed()函数源码实现的版本:

//去掉std::string 字符串前后的空格
void string_trimmed(std::string &str)
{
   	if (str.empty())
		return;
	//判断是否为空格
	auto isSpace = [](char ucs4) ->bool {
		/**
		 * 0x20	space 空格
		 * 0x09 HT - horizontal tab 水平制表符
		 * 0x0A LF - line feed 换行键
		 * 0x0B VT - vertical tab 垂直制表符
		 * 0x0C FF - form feed 换页键
		 * 0x0D CR - carriage return 回车键
		 */
		return ucs4 == 0x20 || (ucs4 <= 0x0d && ucs4 >= 0x09);
	};

	auto begin = str.begin();
	auto end = str.end();
	while ((begin < end) && isSpace(end[-1]))
		--end;

	while ((begin < end) && isSpace(*begin))
		begin++;
	str = std::string(begin, end);
}

使用std::string接口实现版本:

void string_trim(string &s)
{
    if( !s.empty() )
    {
        s.erase(0, s.find_first_not_of(" "));
        s.erase(s.find_last_not_of(" ") + 1);
    }
 }

猜你喜欢

转载自blog.csdn.net/no_say_you_know/article/details/125272606
今日推荐