C++ string trim最佳实践有哪些

   2024-10-11 7220
核心提示:在C++中,可以使用以下方法来实现字符串trim的最佳实践:使用std::string的erase()和find_first_not_of()、find_last_not_of()函

在C++中,可以使用以下方法来实现字符串trim的最佳实践:

使用std::string的erase()和find_first_not_of()、find_last_not_of()函数来去除字符串首尾的空格、制表符等空白字符:
#include <string>#include <iostream>std::string trim(const std::string &s) {    size_t start = s.find_first_not_of(" \t\n\r");    if(start == std::string::npos) {        return "";    }    size_t end = s.find_last_not_of(" \t\n\r");    return s.substr(start, end - start + 1);}int main() {    std::string str = "  hello world  ";    std::cout << trim(str) << std::endl; // 输出:hello world    return 0;}
使用boost库中的trim函数来去除字符串首尾的空格、制表符等空白字符:
#include <boost/algorithm/string.hpp>#include <iostream>int main() {    std::string str = "  hello world  ";    boost::trim(str);    std::cout << str << std::endl; // 输出:hello world    return 0;}
使用C++17中的std::erase_if()和std::isspace()函数来去除字符串首尾的空格、制表符等空白字符:
#include <string>#include <iostream>#include <algorithm>std::string trim(const std::string &s) {    std::string result = s;    result.erase(result.begin(), std::find_if(result.begin(), result.end(), [](unsigned char ch) {        return !std::isspace(ch);    }));    result.erase(std::find_if(result.rbegin(), result.rend(), [](unsigned char ch) {        return !std::isspace(ch);    }).base(), result.end());    return result;}int main() {    std::string str = "  hello world  ";    std::cout << trim(str) << std::endl; // 输出:hello world    return 0;}

这些方法都可以很好地实现字符串trim的功能,选择其中任何一种都可以根据实际情况来进行实现。

 
举报打赏
 
更多>同类维修大全
推荐图文
推荐维修大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号