C++ string trim最佳實(shí)踐有哪些

c++
小樊
89
2024-06-13 15:44:38

在C++中,可以使用以下方法來(lái)實(shí)現(xiàn)字符串trim的最佳實(shí)踐:

  1. 使用std::string的erase()和find_first_not_of()、find_last_not_of()函數(shù)來(lái)去除字符串首尾的空格、制表符等空白字符:
#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庫(kù)中的trim函數(shù)來(lái)去除字符串首尾的空格、制表符等空白字符:
#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()函數(shù)來(lái)去除字符串首尾的空格、制表符等空白字符:
#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;
}

這些方法都可以很好地實(shí)現(xiàn)字符串trim的功能,選擇其中任何一種都可以根據(jù)實(shí)際情況來(lái)進(jìn)行實(shí)現(xiàn)。

0