Table 11.4. Find algorithms
Algorithm name | Description | Functions |
---|---|---|
find_first | Find the first occurrence of a string in the input | find_first() ifind_first() |
find_last | Find the last occurrence of a string in the input | find_last() ifind_last() |
find_nth | Find the nth (zero-indexed) occurrence of a string in the input | find_nth() ifind_nth() |
find_head | Retrieve the head of a string | find_head() |
find_tail | Retrieve the tail of a string | find_tail() |
find_token | Find first matching token in the string | find_token() |
find_regex | Use the regular expression to search the string | find_regex() |
find | Generic find algorithm | find() |
基础示例:
string str1("a1234_first_nth_first_nth_"); boost::iterator_range<string::iterator> ir; // find_first // ifind_first -- 不区分大小写,其它同find_first ir = find_first(str1, "first"); assert(string(ir.begin(), ir.end()) == "first"); // 比较字符串 assert(ir.begin() - str1.begin() == 6 && ir.end()-str1.begin() == 6 + 5); //查看搜索到的字符串所在位置 to_upper(ir); // 利用iterator_range处理搜索到的字符串 assert(str1 == "a1234_FIRST_nth_first_nth_"); to_lower(ir); assert(str1 == "a1234_first_nth_first_nth_"); ir = find_first(str1, "no"); assert(ir.empty()); // 不存在 assert(string(ir.begin(), ir.end()).empty()); // 不存在,仍可构建一个string ostringstream osstr; osstr << find_first( str1, "_first_" ); assert( osstr.str()=="_first_" ); // find_last -- 同findfirst,只是方向相反 // ifind_last -- 不区分大小写,其它同findlast // find_nth ir = find_nth(str1, "nth", 1); assert(ir.begin() - str1.begin() == 22); ir = find_nth(str1, "nth", 0); assert(ir.begin() - str1.begin() == 12); // find_head // find_tail只是方向相反 ir = find_head(str1, 5); transform(ir.begin(), ir.end(), ir.begin(), bind2nd(plus<char>(), 1)); assert(str1 == "b2345_first_nth_first_nth_"); // find_token ir = find_token(str1, is_any_of("irfst")); assert(string(ir.begin(), ir.end()) == "f"); ir = find_token(str1, is_any_of("xfirts"), token_compress_off ); assert(string(ir.begin(), ir.end()) == "f"); ir = find_token(str1, is_any_of("irfst"), token_compress_on ); assert(string(ir.begin(), ir.end()) == "first"); ir = find_token(str1, is_any_of("fitr "), token_compress_on ); assert(string(ir.begin(), ir.end()) == "fir"); // find_regex boost::regex rx("b[0-9]+_"); ir = find_regex(str1, rx); assert(string(ir.begin(), ir.end()) == "b2345_"); // find_all_regex test table 11.4 里没有列出,boost_1_33_0\libs\algorithm\string\test 目录下有 string str2("b1_b22_b333_b4444"); vector<string> tokens; find_all_regex(tokens, str2, rx); assert(tokens.size() == 3); assert(tokens[0] == "b1_"); assert(tokens[1] == "b22_"); assert(tokens[2] == "b333_"); // find ir = find(str1, first_finder(string("b2345_"))); assert(string(ir.begin(), ir.end()) == "b2345_");;