首页 > 代码库 > C++ 字符串处理 重要函数

C++ 字符串处理 重要函数

删除字符串首尾的空格:

string str1="abcdefg";
s.erase(0, s.find_first_not_of(" "));  /// 从头开始找到第一个不为" "的位置; 删除从a到b字符串
str1.erase(s.find_last_not_of(" ") + 1);  /// 从last 开始 找到第一个不为" "的位置。 保留从0到n的字符串

 

 记录:

      find_first_not_of(“ ”)  // 从头开始寻找第一个不为“ ”的位置, 返回的是位置;

      find_last_not_of(" ")  // 从末尾 开始寻找第一个不为“ ”的位置, 返回位置数;

      str1.erase(a,b) ; // 删除 a到b-1的字符串,保留其余的 

      str1.erase(n);  // 保留从开头开始的n个字符串, 其中n是个数 不是位置;

 

PS:  别人写的 trim()  

std::string& trim(std::string &s)
{
    if (s.empty())
    {
        return s;
    }

    s.erase(0, s.find_first_not_of(" ")); 
    s.erase(s.find_last_not_of(" ") + 1);
    return s;
}

 

C++ 字符串处理 重要函数