温馨提示×

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

c++
小樊
84
2024-06-13 15:44:38
栏目: 编程语言

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

  1. 使用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;
}
  1. 使用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;
}
  1. 使用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的功能,选择其中任何一种都可以根据实际情况来进行实现。

0