Boost Library 1.32.0 : String and text processing

来源:互联网 发布:java split正则表达式 编辑:程序博客网 时间:2024/04/30 13:17
网游平台开发中需要使用C++编程,为了有效的利用现有的,成熟的类库,准备对boost库大致浏览一遍,同时将一些心得,记录在blog上。

String and text processing:

1.  conversion/lexical_cast

  lexical_cast类用于字面值的转换,其原型为:

  template<typename Target, typename Source>
  Target lexical_cast(Source arg)

  lexical_cast要求Target支持>>操作,Source支持<<操作,依赖于对stringstream的<<与>>操作完成转换。相对于CRT (C Run-Time Library)中的atoi, atol, atof, lexical_cast支持的数据类型转换更灵活,但运行效率没有进行测试,需要测试后确定是否保留对atoi等的使用。

  无法完成转换时,lexical_cast抛出bad_lexical_cast异常,bad_lexical_cast派生自std::bad_cast

2.  format

  format类用于C++中替代printf like的格式化输出,并且format类是类型安全的。c++中,通过manipulator也可以实现一部分简单的格式化,但是十分有限。
  

  format类在构造时需要指定一个format string,如下:

  format f("%1 + %2 = %3")

  %1代表第一个格式化参数,如果想显示%,那需要用%%来代替。格式化参数并不需要按顺序添加,而且同一个格式化参数也不限于只出现在一处,比如format string可以是"%3 %1 %2 %1"

  format类重载了operator %,比如前面构造的f,可以使用 f % 10 % 20 % 30; 或者 f %10; f % 20; f % 30; 接下来可以使用 << 操作符将 f 输出,或者是 string s = f.str();

  format支持更为复杂的格式化需求,格式为: %[N$][flags][width][.precision]type-char,比如: %3$0#6x

  format类提供了两个方法用于异常处理,分别是:

  unsigned char exceptions(unsigned char newexcept); // query and set exceptions you care
  unsigned char exceptions() const;                             // just query

  exception中可以指定以下的位:

  boost::io::bad_format_string_bit, boost::io::too_few_args_bit, boost::io::too_many_args_bit, boost::io::out_of_range_bit

  另外, boost::io::all_error_bits和boost::io::no_error_bits为别为两个方便全设或清空所有error bit的值。

3.  regex

  regex类就不多记了,需要的时候用就是了,关键是regular expression的语法要记熟。

4.  spirit

  spirit类是 EBNF语法的LL解析器,估计这次不会用到。

5.  tokenizer

  tokenizer是代替CRT中的strtok方法的,并且功能更加强大。tokenizer还提供了interator,方便与其他库的配合应用。

  tokenizer的原型为:

  template <
    class TokenizerFunc = char_delimiters_separator<char>,
    class Iterator = std::string::const_iterator,
    class Type = std::string
>

  boost库中提供了四个预定义的separator: char_separator, escaped_list_separator, offset_separator和char_delimiters_separator,其中最后一个最boost的文档标注为 deprecated

6. string_algo

  与前面的几个类不同,string_algo是一组类的总称,相当于一个sub library了。其位置在boost/algorithm/string目录下,包含的主要内容如下:

  • case_conv.hpp:  大小写转换,包含 to_lower_copy, to_lower, to_upper_copy, to_upper
  • classification.hpp: 字符类别,包含 is_classified(std::ctype_base::mask, locale), is_space, is_alnum, is_upper, is_xdigit等方法
  • cllection_traits.hpp: 一大堆traits类,用于统一char的各种集合类,比如 STL collections, c-style array, null-terminated c-strings等的编程接口。
  • compare.hpp: 字符串字符的functor,提供了is_equal, is_iequal两个predicates.
  • concept.hpp: concept定义,包含FinderConcept和FormatterConcept
  • constants.hpp: 定义了一个enum token_compress_mode_type
  • erase.hpp: 提供了一组从string中移除字符和子串的方法,什么样的都有。
  • find.hpp: 提供了一组从string中寻找子串的方法,允许指定各种寻找子串的条作。
  • finder.hpp:  定义了一组生成string finder的方法
  • formatter.hpp: 定义了一组生成string formatter的方法
  • predicate.hpp: 提供了一组predictate, 包含starts_with, ends_withs, contains等
  • replace.hpp: 提供了一组从string中替换子串的方法
  • split:hpp: 提供了一组分割子串的方法。
  • trim.hpp: trim算法。
原创粉丝点击