boost string_algo库

来源:互联网 发布:wp footer js文件 编辑:程序博客网 时间:2024/05/29 17:48

string_algo库是一个非常全面的字符串算法库,提供了大量的字符串操作函数,如大小写无关比较、修建、特定模式的子串查找等,可以在不适用正则表达式的情况下处理大多数字符串相关问题。
为了使用string_algo组件,需要包含

#include <boost/algorithm/string.hpp>#include <string>#include <iostream>#include <vector>using namespace boost ;using namespace std;int main(){    string str("readme.txt") ;    if (ends_with(str , "txt"))    {        cout<<to_upper_copy(str) + "UPPER"<<std::endl ;        assert(ends_with(str , "txt")) ;    }    replace_first(str , "readme" , "followme") ; //替换第一次在字符中出现的字符    cout<<str<<endl ;    vector<char> v(str.begin() , str.end()) ;    vector<char> v2 = to_upper_copy(erase_first_copy(v , ".txt")) ;    for (auto ch :v2)    {        cout<<ch ;    }    return 1 ;}

输出结果:这里写图片描述

  • 替换查找
    string_algo的替换查找包括:
  • replace/erase_first :替换/删除一个字符串在输入中第一次出现
  • replace/erase_last :替换/删除一个字符串在输入中最后一次出现
  • replace/erase_nth: 替换/删除一个字符串在输入中第n次(从0开始)出现。
  • replace/erase_all : 替换/删除一个字符串在输入中所有出现
  • replace/erase_head : 替换/删除输入开头
  • replace/erase_tail : 替换/删除输入的末尾
    前八个算法每个都有一个i、后缀_copy的组合,后四个只有后缀_copy的两个版本。
    下面有个小例子:
#include <boost/algorithm/string.hpp>#include <string>#include <iostream>#include <vector>using namespace boost ;using namespace std;int main(){    string str = "hello world .txt" ;    cout<<replace_first_copy(str , "hello" , "你好") ; //首次出现替换    replace_last(str , "world" , "china") ;    cout<<str<<endl ;    replace_tail(str , 3 , "xyz") ;    cout<<str<<std::endl ;    cout<<erase_tail_copy(str , 4) ; //删除末尾的四个字符    return 1 ;}
0 0
原创粉丝点击