Trim a string with C++ [2]

I've wrote a blog to discuss how to trim a string in C++. Now I find an other way in high performance, see the implements below: 

#include <string>
#define  STRING_TRIM_DROPS    " \t"

std::string& trim(std::string &s)
{
    static std::string drops = STRING_TRIM_DROPS;  // A char list specifies which characters should be trimmed.

    if (s.empty())
    {
        return s;
    }

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

Yes, using string::erase() method is the fastest way I ever met.

### C++ 中处理字符串查找和裁剪的方法 #### 字符串查找方法 在 C++ 中,`std::string` 类提供了多种用于查找子字符串的方法。最常用的是 `find()` 方法,该方法返回被查找到的子字符串的第一个字符的位置;如果未找到,则返回 `std::string::npos`。 ```cpp #include <iostream> #include <string> int main() { std::string str = "Hello, world!"; size_t pos = str.find("world"); if (pos != std::string::npos) { std::cout << "Found 'world' at position: " << pos << '\n'; } else { std::cout << "'world' not found\n"; } } ``` 除了基本的 `find()` 函数外,还有其他变体可以满足不同的需求: - `rfind(const string& str)`:从右向左寻找第一次出现位置[^1]。 - `find_first_of(const string& str)` 和 `find_last_of(const string& str)`:分别表示从前到后以及从后往前找任意一个指定集合内的字符首次出现的位置[^2]。 - `find_first_not_of(const string& str)` 及其对应的反向版本则用来定位第一个不在给定集中的字符所在之处[^3]。 #### 裁剪(Trim)操作实现 标准库并没有直接提供 trim 功能,但是可以通过组合现有的成员函数轻松创建自定义解决方案来去除首尾空白字符或其他特定字符。下面是一个简单的例子展示如何移除字符串两端多余的空格: ```cpp #include <algorithm> // For remove_if #include <cctype> // For isspace function // Helper lambda expression used within the trim functions. auto is_space = [](unsigned char ch){ return std::isspace(ch); }; /// @brief Removes leading spaces from a given string. inline void ltrim(std::string &s){ s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(is_space))); } /// @brief Removes trailing spaces from a given string. inline void rtrim(std::string &s){ s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(is_space)).base(), s.end()); } /// @brief Combines both left and right trims into one call. inline void trim(std::string &s){ ltrim(s); rtrim(s); } int main(){ std::string sample = " \t Some text with extra whitespace. "; trim(sample); std::cout << "'" << sample << "'\n"; // Output should be without surrounding whitespaces. } ``` 上述代码片段展示了如何通过使用算法库中的工具配合 ctype.h 头文件里的辅助函数完成对输入字符串的有效清理工作。值得注意的是,在实际应用中可能还需要考虑更多类型的不可见字符或特殊符号作为待删除的目标。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值