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;
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); 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()); ostringstream osstr;
osstr << find_first( str1, "_first_" );
assert( osstr.str()=="_first_" );
ir = find_nth(str1, "nth", 1);
assert(ir.begin() - str1.begin() == 22);
ir = find_nth(str1, "nth", 0);
assert(ir.begin() - str1.begin() == 12);
ir = find_head(str1, 5);
transform(ir.begin(), ir.end(), ir.begin(), bind2nd(plus<char>(), 1));
assert(str1 == "b2345_first_nth_first_nth_");
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");
boost::regex rx("b[0-9]+_");
ir = find_regex(str1, rx);
assert(string(ir.begin(), ir.end()) == "b2345_");
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_");
ir = find(str1, first_finder(string("b2345_")));
assert(string(ir.begin(), ir.end()) == "b2345_");;