Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: downloads/boost_1_33_1/doc/html/string_algo/usage.html @ 25

Last change on this file since 25 was 12, checked in by landauf, 17 years ago

added boost

File size: 22.4 KB
Line 
1<html>
2<head>
3<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
4<title>Usage</title>
5<link rel="stylesheet" href="../boostbook.css" type="text/css">
6<meta name="generator" content="DocBook XSL Stylesheets V1.69.1">
7<link rel="start" href="../index.html" title="The Boost C++ Libraries">
8<link rel="up" href="../string_algo.html" title="Chapter 11. Boost String Algorithms Library">
9<link rel="prev" href="release_notes.html" title="Release Notes">
10<link rel="next" href="quickref.html" title="Quick Reference">
11</head>
12<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
13<table cellpadding="2" width="100%">
14<td valign="top"><img alt="boost.png (6897 bytes)" width="277" height="86" src="../../../boost.png"></td>
15<td align="center"><a href="../../../index.htm">Home</a></td>
16<td align="center"><a href="../../../libs/libraries.htm">Libraries</a></td>
17<td align="center"><a href="../../../people/people.htm">People</a></td>
18<td align="center"><a href="../../../more/faq.htm">FAQ</a></td>
19<td align="center"><a href="../../../more/index.htm">More</a></td>
20</table>
21<hr>
22<div class="spirit-nav">
23<a accesskey="p" href="release_notes.html"><img src="../images/prev.png" alt="Prev"></a><a accesskey="u" href="../string_algo.html"><img src="../images/up.png" alt="Up"></a><a accesskey="h" href="../index.html"><img src="../images/home.png" alt="Home"></a><a accesskey="n" href="quickref.html"><img src="../images/next.png" alt="Next"></a>
24</div>
25<div class="section" lang="en">
26<div class="titlepage"><div><div><h3 class="title">
27<a name="string_algo.usage"></a>Usage</h3></div></div></div>
28<div class="toc"><dl>
29<dt><span class="section"><a href="usage.html#id2742478">First Example</a></span></dt>
30<dt><span class="section"><a href="usage.html#id2742674">Case conversion</a></span></dt>
31<dt><span class="section"><a href="usage.html#id2742730">Predicates and Classification</a></span></dt>
32<dt><span class="section"><a href="usage.html#id2742817">Trimming</a></span></dt>
33<dt><span class="section"><a href="usage.html#id2742878">Find algorithms</a></span></dt>
34<dt><span class="section"><a href="usage.html#id2742991">Replace Algorithms</a></span></dt>
35<dt><span class="section"><a href="usage.html#id2743115">Find Iterator</a></span></dt>
36<dt><span class="section"><a href="usage.html#id2743220">Split</a></span></dt>
37</dl></div>
38<div class="section" lang="en">
39<div class="titlepage"><div><div><h4 class="title">
40<a name="id2742478"></a>First Example</h4></div></div></div>
41<p>
42            Using the algorithms is straightforward. Let us have a look at the first example:
43        </p>
44<pre class="programlisting">
45    #include &lt;boost/algorithm/string.hpp&gt;
46    using namespace std;
47    using namespace boost;
48   
49    // ...
50
51    string str1(" hello world! ");
52    to_upper(str1);  // str1 == " HELLO WORLD! "
53    trim(str1);      // str1 == "HELLO WORLD!"
54
55    string str2=
56       to_lower_copy(
57          ireplace_first_copy(
58             str1,"hello","goodbye")); // str2 == "goodbye world!"
59        </pre>
60<p>
61            This example converts str1 to upper case and trims spaces from the start and the end
62            of the string. str2 is then created as a copy of str1 with "hello" replaced with "goodbye".
63            This example demonstrates several important concepts used in the library:
64        </p>
65<div class="itemizedlist"><ul type="disc">
66<li>
67<p><span class="bold"><strong>Container parameters:</strong></span>
68                    Unlike in the STL algorithms, parameters are not specified only in the form
69                    of iterators. The STL convention allows for great flexibility,
70                    but it has several limitations. It is not possible to <span class="emphasis"><em>stack</em></span> algorithms together,
71                    because a container is passed in two parameters. Therefore it is not possible to use
72                    a return value from another algorithm. It is considerably easier to write
73                    <code class="computeroutput">to_lower(str1)</code>, than <code class="computeroutput">to_lower(str1.begin(), str1.end())</code>.
74                </p>
75<p>
76                    The magic of <a href="../../../libs/range/index.html" target="_top">Boost.Range</a> 
77                    provides a uniform way of handling different string types.
78                    If there is a need to pass a pair of iterators,
79                    <a href="../../../libs/range/doc/utility_class.html" target="_top"><code class="computeroutput">boost::iterator_range</code></a>
80                    can be used to package iterators into a structure with a compatible interface.
81                </p>
82</li>
83<li><p><span class="bold"><strong>Copy vs. Mutable:</strong></span>
84                    Many algorithms in the library are performing a transformation of the input.
85                    The transformation can be done in-place, mutating the input sequence, or a copy
86                    of the transformed input can be created, leaving the input intact. None of
87                    these possibilities is superior to the other one and both have different
88                    advantages and disadvantages. For this reason, both are provided with the library.
89                </p></li>
90<li><p><span class="bold"><strong>Algorithm stacking:</strong></span>
91                    Copy versions return a transformed input as a result, thus allow a simple chaining of
92                    transformations within one expression (i.e. one can write <code class="computeroutput">trim_copy(to_upper_copy(s))</code>).
93                    Mutable versions have <code class="computeroutput">void</code> return, to avoid misuse.
94                </p></li>
95<li><p><span class="bold"><strong>Naming:</strong></span>
96                    Naming follows the conventions from the Standard C++ Library. If there is a
97                    copy and a mutable version of the same algorithm, the mutable version has no suffix
98                    and the copy version has the suffix <span class="emphasis"><em>_copy</em></span>.
99                    Some algorithms have the prefix <span class="emphasis"><em>i</em></span> 
100                    (e.g. <code class="computeroutput"><a href="../ifind_first.html" title="Function template ifind_first">ifind_first()</a></code>).
101                    This prefix identifies that the algorithm works in a case-insensitive manner.
102                </p></li>
103</ul></div>
104<p>
105            To use the library, include the <code class="computeroutput"><a href="reference.html#id2552179" title="Header &lt;boost/algorithm/string.hpp&gt;">boost/algorithm/string.hpp</a></code> header.
106            If the regex related functions are needed, include the
107            <code class="computeroutput"><a href="reference.html#id2573542" title="Header &lt;boost/algorithm/string_regex.hpp&gt;">boost/algorithm/string_regex.hpp</a></code> header.
108        </p>
109</div>
110<div class="section" lang="en">
111<div class="titlepage"><div><div><h4 class="title">
112<a name="id2742674"></a>Case conversion</h4></div></div></div>
113<p>
114            STL has a nice way of converting character case. Unfortunately, it works only
115            for a single character and we want to convert a string,
116        </p>
117<pre class="programlisting">
118    string str1("HeLlO WoRld!");
119    to_upper(str1); // str1=="HELLO WORLD!"
120        </pre>
121<p><code class="computeroutput"><a href="../to_upper.html" title="Function template to_upper">to_upper()</a></code> and <code class="computeroutput"><a href="../to_lower.html" title="Function template to_lower">to_lower()</a></code> convert the case of
122            characters in a string using a specified locale.
123        </p>
124<p>
125            For more information see the reference for <code class="computeroutput"><a href="reference.html#id2352615" title="Header &lt;boost/algorithm/string/case_conv.hpp&gt;">boost/algorithm/string/case_conv.hpp</a></code>.
126        </p>
127</div>
128<div class="section" lang="en">
129<div class="titlepage"><div><div><h4 class="title">
130<a name="id2742730"></a>Predicates and Classification</h4></div></div></div>
131<p>
132            A part of the library deals with string related predicates. Consider this example:
133        </p>
134<pre class="programlisting">
135    bool is_executable( string&amp; filename )
136    {
137        return
138            iends_with(filename, ".exe") ||
139            iends_with(filename, ".com");
140    }
141
142    // ...
143    string str1("command.com");
144    cout
145        &lt;&lt; str1
146        &lt;&lt; is_executable("command.com")? "is": "is not"
147        &lt;&lt; "an executable"
148        &lt;&lt; endl; // prints "command.com is an executable"
149   
150    //..
151    char text1[]="hello world!";
152    cout
153        &lt;&lt; text1
154        &lt;&lt; all( text1, is_lower() )? "is": "is not"
155        &lt;&lt; " written in the lower case"
156        &lt;&lt; endl; // prints "hello world! is written in the lower case"
157        </pre>
158<p>
159            The predicates determine whether if a substring is contained in the input string
160            under various conditions. The conditions are: a string starts with the substring,
161            ends with the substring,
162            simply contains the substring or if both strings are equal. See the reference for
163            <code class="computeroutput"><a href="reference.html#id2589054" title="Header &lt;boost/algorithm/string/predicate.hpp&gt;">boost/algorithm/string/predicate.hpp</a></code> for more details.
164        </p>
165<p> 
166            In addition the algorithm <code class="computeroutput"><a href="../all.html" title="Function template all">all()</a></code> checks
167            all elements of a container to satisfy a condition specified by a predicate.
168            This predicate can be any unary predicate, but the library provides a bunch of
169            useful string-related predicates and combinators ready for use.
170            These are located in the <code class="computeroutput"><a href="reference.html#id2336200" title="Header &lt;boost/algorithm/string/classification.hpp&gt;">boost/algorithm/string/classification.hpp</a></code> header.
171            Classification predicates can be combined using logical combinators to form
172            a more complex expressions. For example: <code class="computeroutput">is_from_range('a','z') || is_digit()</code></p>
173</div>
174<div class="section" lang="en">
175<div class="titlepage"><div><div><h4 class="title">
176<a name="id2742817"></a>Trimming</h4></div></div></div>
177<p>
178            When parsing the input from a user, strings usually have unwanted leading or trailing
179            characters. To get rid of them, we need trim functions:
180        </p>
181<pre class="programlisting">
182    string str1="     hello world!     ";
183    string str2=trim_left_copy(str1);   // str2 == "hello world!     "
184    string str3=trim_right_copy(str2);  // str3 == "     hello world!"
185    trim(str1);                         // str1 == "hello world!"
186
187    string phone="00423333444";
188    // remove leading 0 from the phone number
189    trim_left_if(phone,is_any_of("0")); // phone == "423333444"
190        </pre>
191<p>
192            It is possible to trim the spaces on the right, on the left or on both sides of a string.
193            And for those cases when there is a need to remove something else than blank space, there
194            are <span class="emphasis"><em>_if</em></span> variants. Using these, a user can specify a functor which will
195            select the <span class="emphasis"><em>space</em></span> to be removed. It is possible to use classification
196            predicates like <code class="computeroutput"><a href="../is_digit.html" title="Function is_digit">is_digit()</a></code> mentioned in the previous paragraph.
197            See the reference for the <code class="computeroutput"><a href="reference.html#id2573553" title="Header &lt;boost/algorithm/string/trim.hpp&gt;">boost/algorithm/string/trim.hpp</a></code>.
198        </p>
199</div>
200<div class="section" lang="en">
201<div class="titlepage"><div><div><h4 class="title">
202<a name="id2742878"></a>Find algorithms</h4></div></div></div>
203<p>
204            The library contains a set of find algorithms. Here is an example:
205        </p>
206<pre class="programlisting">
207    char text[]="hello dolly!";
208    iterator_range&lt;char*&gt; result=find_last(text,"ll");
209
210    transform( result.begin(), result.end(), result.begin(), bind2nd(plus&lt;char&gt;(), 1) );
211    // text = "hello dommy!"           
212
213    to_upper(result); // text == "hello doMMy!"
214
215    // iterator_range is convertible to bool
216    if(find_first(text, "dolly"))
217    {
218        cout &lt;&lt; "Dolly is there" &lt;&lt; endl;
219    }
220        </pre>
221<p>
222            We have used <code class="computeroutput"><a href="../find_last.html" title="Function template find_last">find_last()</a></code> to search the <code class="computeroutput">text</code> for "ll".
223            The result is given in the <a href="../../../libs/range/doc/utility_class.html" target="_top"><code class="computeroutput">boost::iterator_range</code></a>.
224            This range delimits the
225            part of the input which satisfies the find criteria. In our example it is the last occurrence of "ll".
226           
227            As we can see, input of the <code class="computeroutput"><a href="../find_last.html" title="Function template find_last">find_last()</a></code> algorithm can be also
228            char[] because this type is supported by
229            <a href="../../../libs/range/index.html" target="_top">Boost.Range</a>.
230
231            The following lines transform the result. Notice that
232            <a href="../../../libs/range/doc/utility_class.html" target="_top"><code class="computeroutput">boost::iterator_range</code></a> has familiar
233            <code class="computeroutput">begin()</code> and <code class="computeroutput">end()</code> methods, so it can be used like any other STL container.
234            Also it is convertible to bool therefore it is easy to use find algorithms for a simple containment checking.
235        </p>
236<p>
237            Find algorithms are located in <code class="computeroutput"><a href="reference.html#id2487443" title="Header &lt;boost/algorithm/string/find.hpp&gt;">boost/algorithm/string/find.hpp</a></code>.
238        </p>
239</div>
240<div class="section" lang="en">
241<div class="titlepage"><div><div><h4 class="title">
242<a name="id2742991"></a>Replace Algorithms</h4></div></div></div>
243<p>
244            Find algorithms can be used for searching for a specific part of string. Replace goes one step
245            further. After a matching part is found, it is substituted with something else. The substitution is computed
246            from the original, using some transformation.
247        </p>
248<pre class="programlisting">
249    string str1="Hello  Dolly,   Hello World!"
250    replace_first(str1, "Dolly", "Jane");      // str1 == "Hello  Jane,   Hello World!"
251    replace_last(str1, "Hello", "Goodbye");    // str1 == "Hello  Jane,   Goodbye World!"
252    erase_all(str1, " ");                      // str1 == "HelloJane,GoodbyeWorld!"
253    erase_head(str1, 6);                       // str1 == "Jane,GoodbyeWorld!"
254        </pre>
255<p>
256            For the complete list of replace and erase functions see the
257            <a href="reference.html" title="Reference">reference</a>.
258            There is a lot of predefined function for common usage, however, the library allows you to
259            define a custom <code class="computeroutput">replace()</code> that suits a specific need. There is a generic <code class="computeroutput"><a href="../find_format.html" title="Function template find_format">find_format()</a></code> 
260            function which takes two parameters.
261            The first one is a <a href="concept.html#string_algo.finder_concept" title="Finder Concept">Finder</a> object, the second one is
262            a <a href="concept.html#string_algo.formatter_concept" title="Formatter concept">Formatter</a> object.
263            The Finder object is a functor which performs the searching for the replacement part. The Formatter object
264            takes the result of the Finder (usually a reference to the found substring) and creates a
265            substitute for it. Replace algorithm puts these two together and makes the desired substitution.
266        </p>
267<p>
268            Check <code class="computeroutput"><a href="reference.html#id2553153" title="Header &lt;boost/algorithm/string/replace.hpp&gt;">boost/algorithm/string/replace.hpp</a></code>, <code class="computeroutput"><a href="reference.html#id2571451" title="Header &lt;boost/algorithm/string/erase.hpp&gt;">boost/algorithm/string/erase.hpp</a></code> and
269            <code class="computeroutput"><a href="reference.html#id2441187" title="Header &lt;boost/algorithm/string/find_format.hpp&gt;">boost/algorithm/string/find_format.hpp</a></code> for reference.
270        </p>
271</div>
272<div class="section" lang="en">
273<div class="titlepage"><div><div><h4 class="title">
274<a name="id2743115"></a>Find Iterator</h4></div></div></div>
275<p>
276            An extension to find algorithms it the Find Iterator. Instead of searching for just a one part of a string,
277            the find iterator allows us to iterate over the substrings matching the specified criteria.
278            This facility is using the <a href="concept.html#string_algo.finder_concept" title="Finder Concept">Finder</a> to incrementally
279            search the string.
280            Dereferencing a find iterator yields an <a href="../../../libs/range/doc/utility_class.html" target="_top"><code class="computeroutput">boost::iterator_range</code></a> 
281            object, that delimits the current match.
282        </p>
283<p>
284            There are two iterators provided <code class="computeroutput"><a href="../find_iterator.html" title="Class template find_iterator">find_iterator</a></code> and
285            <code class="computeroutput"><a href="../split_iterator.html" title="Class template split_iterator">split_iterator</a></code>. The former iterates over substrings that are found using the specified
286            Finder. The latter iterates over the gaps between these substrings.
287        </p>
288<pre class="programlisting">
289    string str1("abc-*-ABC-*-aBc");
290    // Find all 'abc' substrings (ignoring the case)
291    // Create a find_iterator
292    typedef find_iterator&lt;string::iterator&gt; string_find_iterator;
293    for(string_find_iterator It=
294            make_find_iterator(str1, first_finder("abc", is_iequal()));
295        It!=string_find_iterator();
296        ++It)
297    {
298        cout &lt;&lt; copy_range&lt;std::string&gt;(*It) &lt;&lt; endl;
299    }
300
301    // Output will be:
302    // abc
303    // ABC
304    // aBC
305   
306    typedef split_iterator&lt;string::iterator&gt; string_split_iterator;
307    for(string_find_iterator It=
308        make_split_iterator(str1, first_finder("-*-", is_iequal()));
309        It!=string_find_iterator();
310        ++It)
311    {
312        cout &lt;&lt; copy_range&lt;std::string&gt;(*It) &lt;&lt; endl;
313    }
314
315    // Output will be:
316    // abc
317    // ABC
318    // aBC
319        </pre>
320<p>
321            Note that the find iterators have only one template parameter. It is the base iterator type.
322            The Finder is specified at runtime. This allows us to typedef a find iterator for
323            common string types and reuse it. Additionally make_*_iterator functions help
324            to construct a find iterator for a particular range.
325        </p>
326<p>
327            See the reference in <code class="computeroutput"><a href="reference.html#id2382464" title="Header &lt;boost/algorithm/string/find_iterator.hpp&gt;">boost/algorithm/string/find_iterator.hpp</a></code>.
328        </p>
329</div>
330<div class="section" lang="en">
331<div class="titlepage"><div><div><h4 class="title">
332<a name="id2743220"></a>Split</h4></div></div></div>
333<p>
334            Split algorithms are an extension to the find iterator for one common usage scenario.
335            These algorithms use a find iterator and store all matches into the provided
336            container. This container must be able to hold copies (e.g. <code class="computeroutput">std::string</code>) or
337            references (e.g. <code class="computeroutput">iterator_range</code>) of the extracted substrings.
338        </p>
339<p>
340            Two algorithms are provided. <code class="computeroutput"><a href="../find_all.html" title="Function template find_all">find_all()</a></code> finds all copies
341            of a string in the input. <code class="computeroutput"><a href="../id2580251.html" title="Function template split">split()</a></code> splits the input into parts.
342        </p>
343<pre class="programlisting">
344    string str1("hello abc-*-ABC-*-aBc goodbye");
345
346    typedef vector&lt; iterator_range&lt;string::iterator&gt; &gt; find_vector_type;
347   
348    find_vector_type FindVec; // #1: Search for separators
349    ifind_all( FindVec, str1, "abc" ); // FindVec == { [abc],[ABC],[aBc] }
350
351    typedef vector&lt; string &gt; split_vector_type;
352   
353    split_vector_type SplitVec; // #2: Search for tokens
354    split( SplitVec, str1, is_any_of("-*") ); // SplitVec == { "hello abc","ABC","aBc goodbye" }
355        </pre>
356<p><code class="computeroutput">[hello]</code> designates an <code class="computeroutput">iterator_range</code> delimiting this substring.                       
357        </p>
358<p>
359            First example show how to construct a container to hold references to all extracted
360            substrings. Algorithm <code class="computeroutput"><a href="../ifind_all.html" title="Function template ifind_all">ifind_all()</a></code> puts into FindVec references
361            to all substrings that are in case-insensitive manner equal to "abc".
362        </p>
363<p>
364            Second example uses <code class="computeroutput"><a href="../id2580251.html" title="Function template split">split()</a></code> to split string str1 into parts
365            separated by characters '-' or '*'. These parts are then put into the SplitVec.
366            It is possible to specify if adjacent separators are concatenated or not.
367        </p>
368<p>
369            More information can be found in the reference: <code class="computeroutput"><a href="reference.html#id2541245" title="Header &lt;boost/algorithm/string/split.hpp&gt;">boost/algorithm/string/split.hpp</a></code>.
370        </p>
371</div>
372</div>
373<table width="100%"><tr>
374<td align="left"><small><p>Last revised: December 01, 2005 at 13:42:02 GMT</p></small></td>
375<td align="right"><small>Copyright © 2002-2004 Pavol Droba</small></td>
376</tr></table>
377<hr>
378<div class="spirit-nav">
379<a accesskey="p" href="release_notes.html"><img src="../images/prev.png" alt="Prev"></a><a accesskey="u" href="../string_algo.html"><img src="../images/up.png" alt="Up"></a><a accesskey="h" href="../index.html"><img src="../images/home.png" alt="Home"></a><a accesskey="n" href="quickref.html"><img src="../images/next.png" alt="Next"></a>
380</div>
381</body>
382</html>
Note: See TracBrowser for help on using the repository browser.