boost 字符串处理

#include <iostream>
using namespace std;



//进行字符串、整数/浮点数之间的字面转换

#include <boost/lexical_cast.hpp>
void test_lexical_cast()
{

    int a = lexical_cast<int>("123");//<>中的为目标类型
    double b = lexical_cast<double>("123.0123456789");
    // unsigned int a1 = lexical_cast<unsigned int>("4294967296");// 超出范围报错
    unsigned int a2 = lexical_cast<unsigned int>("-1");// 4294967295
    double b1 = lexical_cast<double>("123.0123456789",6);// 参数2指定长度,超过参数1长度则抛出异常,b1 = 123.01
    lexical_cast<bool>("1");// 转换为bool时参数只能是0/1,其他均报错
    string s0 = lexical_cast<string>(a);
    string s1 = lexical_cast<string>(b);
    cout << "number: " << a << "  " << b << endl;//number: 123  123.012
    cout << "string: " << s0 << "  " << s1 << endl;//string: 123  123.0123456789
    int c = 0;
    try{
        c = lexical_cast<int>("abcd");
    }
    catch (boost::bad_lexical_cast& e){
        cout << e.what() << endl;//bad lexical cast: source type value could not be interpreted as target
    }
    
    double res = 0;
    bool flag = boost::conversion::try_lexical_convert("1234.5x6", res);// 该函数不会抛出异常,返回是否转化成功
}



// 格式

#include <boost/format.hpp> 

void test_format()
{
    // 用法1(类似printf)
    cout << format("%s:%d + %d = %d\n") % "sum" % 1 % 2 % (1 + 2);

    // 用法2
    //format构造函数中 %number% 指定匹配参数的位置,函数后面跟参数列表,跟在%后面
    std::cout << boost::format("writing %1%, x=%2% : %3%-th try") % "toto" % 40.23 % 50 << std::endl;//writing toto, x=40.23 : 50-th try
    boost::format f("a=%1%,b=%2%,c=%3%,a=%2%");// 后续要是用到比如f.str(),则不能%4% ,因为没有第四个参数,否则运行报错
    f % "string" % 2 % 10.0;// 后续要是用到比如f.str(),不能 再添加%,因为上面没有匹配%%,否则运行报错
    std::cout << f.str() << std::endl;//a=string,b=2,c=10,a=2

    std::cout << boost::format("adasda %1%  %2%  %3% ") % 123 % 78 % 464 << std::endl;//adasda 123  78  464
    boost::format f1("%1% %2% %3% %1%");
    f1 % 111111 % 22222222222;
    f1 % 33333;
    std::cout << f1.str() << std::endl;//111111 22222222222 33333 111111

    // 清空缓存数据
    f1.clear();
    f1 % 44 % 55 % 66;// 重新格式化字符串
    std::cout << f1.str() << std::endl;//44 55 66 44

    // 清空缓存数据并改用新的格式
    f1.parse("%2% %2% %3% %3%");// f1.parse("%2% %2% %3% %3%") %  % 44 % 55 % 66;
    f1 % 44 % 55 % 66;
    std::cout << f1.str() << std::endl;//44 55 66 66
}



// 字符串算法

#include <boost/algorithm/string.hpp>

static inline void replaceEmojiUnicodeToChar(std::string& str)
{
    map<string, string> emoji_map;
    emoji_map.insert(map<string, string>::value_type("zzz", "500"));

    for (std::map<std::string, std::string>::iterator it = emoji_map.begin(); it != emoji_map.end(); it++)
    {
        boost::algorithm::replace_all(str, it->first, it->second);// 在str中将参数二【第一组字符串(it->first)】换成参数三【it->second】
        // str = 500zss"
    }
}

void test_string()
{
    using namespace boost;
    string str("readme.txt");
    if (ends_with(str, "txt"))
    {
        cout << to_upper_copy(str) + "UPPER" << endl;//README.TXTUPPER
        assert(ends_with(str, "txt"));
    }
    replace_first(str, "readme", "followme");
    cout << str << endl;//followme.txt
    vector<char> v(str.begin(), str.end());
    vector<char> v2 = to_upper_copy(erase_first_copy(v, "txt"));
    for (uint32_t i = 0; i < v2.size(); ++i)
        cout << v2[i];//FOLLOWME.
    cout << endl;
    for (uint32_t i = 0; i < v.size(); ++i)
        cout << v[i];//followme.txt
    cout << endl;



    replaceEmojiUnicodeToChar(str1);
    cout << "str1 === " << str1 << endl;//str1 === 500zss
}



//字符串分割

#include <boost/tokenizer.hpp>
void test_tokenizer()
{
    string s("This is , a ,test!");
    boost::tokenizer<> tok2(s);//默认',',' '为分割字符
    for (boost::tokenizer<>::iterator beg = tok2.begin(); beg != tok2.end(); ++beg)
        cout << *beg << " ";//This is a test
    cout << endl;

    boost::tokenizer<boost::escaped_list_separator<char>> tok(s);//','为分隔符
    for (boost::tokenizer<boost::escaped_list_separator<char>>::iterator beg = tok.begin(); beg != tok.end(); ++beg)
        cout << *beg << " ";//This is   a  test!
    cout << endl;

    typedef boost::tokenizer<boost::char_separator<char> > Tok;//' ’为分隔符
    boost::char_separator<char> sep3;
    Tok tok3(s, sep3);
    for (Tok::iterator tok_iter = tok3.begin(); tok_iter != tok3.end(); ++tok_iter)
        std::cout << "<" << *tok_iter << "> ";//<This> <is> <,> <a> <,> <test> <!>
    cout << endl;

    boost::char_separator<char> sep("-; ,");
    boost::tokenizer<boost::char_separator<char>> tok1(s, sep);
    for (boost::tokenizer<boost::char_separator<char>>::iterator beg = tok1.begin(); beg != tok1.end(); ++beg)
        cout << *beg << " ";//This is a test!
    cout << endl;


    std::string str = ";;Hello|world||-foo--bar;yow;baz|";
    typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
    boost::char_separator<char> sep1("-;", "|", boost::keep_empty_tokens);
    tokenizer tokens(str, sep1);
    for (tokenizer::iterator tok_iter = tokens.begin(); tok_iter != tokens.end(); ++tok_iter)
        std::cout << "<" << *tok_iter << ">";//<><><Hello><|><world><|><><|><><foo><><bar><yow><baz><|><>
    cout << endl;
}

// 用c库中的strtok_s惊醒字符串分割
{
typedef std::pair<uint16_t,uint16_t> TimePoint;		// 时间点
typedef std::pair<TimePoint,TimePoint> TimeSegment;	// 时间段

	std::vector<TimeSegment> m_dragonModeOpenTimeVec;// 开放时间
	std::string dragonModeOpenTimeStr = "00:00~02:00|09:00~10:00|12:00~14:00|18:00~20:00|22:00~0:00"
	if (!dragonModeOpenTimeStr.empty())
	{
		m_dragonModeOpenTimeVec.clear();
		char * openTimeStr = const_cast<char *>(dragonModeOpenTimeStr.c_str());
		char * token = NULL;
		char * time = NULL;
		TimePoint leftTime(0,0),rightTime(0,0);//00:00~02:00
		while (token = strtok_s(NULL, "|", &openTimeStr))
		{
			if (time = strtok_s(NULL, ":", &token))
				leftTime.first = atoi(time);
			if (time = strtok_s(NULL, "~", &token))
				leftTime.second = atoi(time);
			if (time = strtok_s(NULL, ":", &token))
				rightTime.first = atoi(time);
			if (time = strtok_s(NULL, ":", &token))
				rightTime.second = atoi(time);
			TimeSegment timeSegment(leftTime,rightTime);
			m_dragonModeOpenTimeVec.push_back(timeSegment);
		}
	}
}
// 正则

#include <boost/xpressive/xpressive_dynamic.hpp>
void test_cregex()
{
    using namespace boost::xpressive;
    cregex reg = cregex::compile("a.c");
    assert(regex_match("abc", reg));// true
//    assert(regex_match("a + c", reg));//false
    assert(!regex_match("ac", reg));//false
    assert(!regex_match("abd", reg));//false
    cout << "match Success" << endl;
}



// 类型的转化
void test_any()
{
    using namespace boost;
    typedef std::vector<boost::any> many;
    many a;
    a.push_back(2);
    a.push_back(string("test"));
    for (unsigned int i = 0; i < a.size(); ++i)
    {
        cout << a[i].type().name() << endl;// 类型名
        try
        {
            int result = any_cast<int>(a[i]);//int    class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >
            cout << result << endl;// 2
        }
        catch (boost::bad_any_cast & ex)
        {
            cout << "cast error:" << ex.what() << endl;//cast error:boost::bad_any_cast: failed conversion using boost::any_cast
        }
    }
}

int main()
{
    test_lexical_cast();
    test_format();
    test_string();
    test_tokenizer();
    test_cregex();
    test_any();

    // Boost中string的操作trim用法
    //https://blog.csdn.net/zhangxiong1985/article/details/84453292

    // Boost中string的操作split用法
    https://blog.csdn.net/zhangxiong1985/article/details/84503072

    // Boost中string的erase及replace用法
    https://blog.csdn.net/zhangxiong1985/article/details/84503341
    getchar();
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值