«

boost的字符串操作

benojan • 2023-02-09 12:23 • 505 次点击 • c/c++


头文件

#include <boost/algorithm/string.hpp>

功能

  1. 字符串切割

    boost::algorithm::split()
    using namespace boost::algorithm;
    int main()
    {
        std::string s = "Boost C++ Libraries";
        std::vector<std::string> v;
        split(v, s, is_space());
        std::cout << v.size() << std::endl;
    }
    // 内置的方式
    using algorithm::is_classified;
    using algorithm::is_space; // 空白
    using algorithm::is_alnum; // 数字+字母
    using algorithm::is_alpha; // 字母
    using algorithm::is_cntrl;
    using algorithm::is_digit; // 数字
    using algorithm::is_graph;
    using algorithm::is_lower; // 小写字母
    using algorithm::is_upper; // 大写字母
    using algorithm::is_print;
    using algorithm::is_punct;
    using algorithm::is_xdigit;
    using algorithm::is_any_of; // 字符串中的任意字符
    using algorithm::is_from_range;
  2. 去除首尾字符-默认为空白字符

    boost::algorithm::trim_left_copy(str)
    boost::algorithm::trim_right_copy(str)
    boost::algorithm::trim_copy(str)
    // 指定字符
    boost::algorithm::trim_left_copy_if(str, boost::algorithm::is_any_of("+-")
    boost::algorithm::trim_right_copy_if(str, boost::algorithm::is_any_of("+-")))
    boost::algorithm::trim_copy_if(str, boost::algorithm::is_any_of(" \t\n"))
  3. 大小写转换

    boost::algorithm::to_upper(str)
    boost::algorithm::to_lower(str)
    // copy函数返回一个大小写变换之后的副本
    boost::algorithm::to_upper_copy(str)
    boost::algorithm::to_upper_copy(str)
  4. 移除指定字符串

    // 移除第一个出现的指定字符串
    erase_first_copy(str, "strOrChar")
    // 移除第n个出现的指定字符串
    erase_nth_copy(str, "strOrChar", 0)
    // 移除最后出现的指定字符串
    erase_last_copy(str, "strOrChar")
    // 移除所有出现的指定字符串
    erase_all_copy(str, "strOrChar")
    // 移除头部的指定字符串
    erase_head_copy(str, 5)
    // 移除尾部的指定字符串
    erase_tail_copy(str, 5)
  5. 查找子串

    boost::algorithm::find_first(str, "substr")
    boost::algorithm::find_last()
    boost::algorithm::find_nth()
    boost::algorithm::find_head()
    boost::algorithm::find_tail()
  6. 字符串拼接

    boost::algorithm::join()
    using namespace boost::algorithm;
    int main() {
        std::vector<std::string> v{"Boost", "C++", "Libraries"};
        std::cout << join(v, " ") << std::endl;
    }
  7. 字符串替换

    boost::algorithm::replace_first_copy(s, "B", "D")
    boost::algorithm::replace_nth_copy(s, "i", 0, "D")
    boost::algorithm::replace_last_copy(s, "i", "D")
    boost::algorithm::replace_all_copy(s, "i", "D")
    boost::algorithm::replace_head_copy(s, 5, "DoAAA")
    boost::algorithm::replace_tail_copy(s, 8, "BecCCC")

c++ boost 字符串操作