OSDN Git Service

e49a166c0c5899eeebd92850eac540684fa4f13c
[pf3gnuchains/gcc-fork.git] / libstdc++-v3 / docs / html / 21_strings / howto.html
1 <html>
2 <head>
3    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
4    <meta name="AUTHOR" content="pme@gcc.gnu.org (Phil Edwards)" />
5    <meta name="KEYWORDS" content="HOWTO, libstdc++, GCC, g++, libg++, STL" />
6    <meta name="DESCRIPTION" content="HOWTO for the libstdc++ chapter 21." />
7    <meta name="GENERATOR" content="vi and eight fingers" />
8    <title>libstdc++-v3 HOWTO:  Chapter 21</title>
9 <link rel="StyleSheet" href="../lib3styles.css" />
10 </head>
11 <body>
12
13 <h1 class="centered"><a name="top">Chapter 21:  Strings</a></h1>
14
15 <p>Chapter 21 deals with the C++ strings library (a welcome relief).
16 </p>
17
18
19 <!-- ####################################################### -->
20 <hr />
21 <h1>Contents</h1>
22 <ul>
23    <li><a href="#1">MFC's CString</a></li>
24    <li><a href="#2">A case-insensitive string class</a></li>
25    <li><a href="#3">Breaking a C++ string into tokens</a></li>
26    <li><a href="#4">Simple transformations</a></li>
27    <li><a href="#5">Making strings of arbitrary character types</a></li>
28 </ul>
29
30 <hr />
31
32 <!-- ####################################################### -->
33
34 <h2><a name="1">MFC's CString</a></h2>
35    <p>A common lament seen in various newsgroups deals with the Standard
36       string class as opposed to the Microsoft Foundation Class called
37       CString.  Often programmers realize that a standard portable
38       answer is better than a proprietary nonportable one, but in porting
39       their application from a Win32 platform, they discover that they
40       are relying on special functions offered by the CString class.
41    </p>
42    <p>Things are not as bad as they seem.  In
43       <a href="http://gcc.gnu.org/ml/gcc/1999-04n/msg00236.html">this
44       message</a>, Joe Buck points out a few very important things:
45    </p>
46       <ul>
47          <li>The Standard <code>string</code> supports all the operations
48              that CString does, with three exceptions.
49          </li>
50          <li>Two of those exceptions (whitespace trimming and case 
51              conversion) are trivial to implement.  In fact, we do so
52              on this page.
53          </li>
54          <li>The third is <code>CString::Format</code>, which allows formatting
55              in the style of <code>sprintf</code>.  This deserves some mention:
56          </li>
57       </ul>
58    <p><a name="1.1internal"> <!-- Coming from Chapter 27 -->
59       The old libg++ library had a function called form(), which did much
60       the same thing.  But for a Standard solution, you should use the
61       stringstream classes.  These are the bridge between the iostream
62       hierarchy and the string class, and they operate with regular
63       streams seamlessly because they inherit from the iostream
64       hierarchy.  An quick example:
65       </a>
66    </p>
67    <pre>
68    #include &lt;iostream&gt;
69    #include &lt;string&gt;
70    #include &lt;sstream&gt;
71
72    string f (string&amp; incoming)     // incoming is "foo  N"
73    {
74        istringstream   incoming_stream(incoming);
75        string          the_word;
76        int             the_number;
77
78        incoming_stream &gt;&gt; the_word        // extract "foo"
79                        &gt;&gt; the_number;     // extract N
80
81        ostringstream   output_stream;
82        output_stream &lt;&lt; "The word was " &lt;&lt; the_word
83                      &lt;&lt; " and 3*N was " &lt;&lt; (3*the_number);
84
85        return output_stream.str();
86    } </pre>
87    <p>A serious problem with CString is a design bug in its memory
88       allocation.  Specifically, quoting from that same message:
89    </p>
90    <pre>
91    CString suffers from a common programming error that results in
92    poor performance.  Consider the following code:
93    
94    CString n_copies_of (const CString&amp; foo, unsigned n)
95    {
96            CString tmp;
97            for (unsigned i = 0; i &lt; n; i++)
98                    tmp += foo;
99            return tmp;
100    }
101    
102    This function is O(n^2), not O(n).  The reason is that each +=
103    causes a reallocation and copy of the existing string.  Microsoft
104    applications are full of this kind of thing (quadratic performance
105    on tasks that can be done in linear time) -- on the other hand,
106    we should be thankful, as it's created such a big market for high-end
107    ix86 hardware. :-)
108    
109    If you replace CString with string in the above function, the
110    performance is O(n).
111    </pre>
112    <p>Joe Buck also pointed out some other things to keep in mind when
113       comparing CString and the Standard string class:
114    </p>
115       <ul>
116          <li>CString permits access to its internal representation; coders
117              who exploited that may have problems moving to <code>string</code>.
118          </li>
119          <li>Microsoft ships the source to CString (in the files
120              MFC\SRC\Str{core,ex}.cpp), so you could fix the allocation
121              bug and rebuild your MFC libraries.
122              <em><strong>Note:</strong> It looks like the the CString shipped
123              with VC++6.0 has fixed this, although it may in fact have been
124              one of the VC++ SPs that did it.</em>
125          </li>
126          <li><code>string</code> operations like this have O(n) complexity
127              <em>if the implementors do it correctly</em>.  The libstdc++
128              implementors did it correctly.  Other vendors might not.
129          </li>
130          <li>While parts of the SGI STL are used in libstdc++-v3, their
131              string class is not.  The SGI <code>string</code> is essentially
132              <code>vector&lt;char&gt;</code> and does not do any reference
133              counting like libstdc++-v3's does.  (It is O(n), though.)
134              So if you're thinking about SGI's string or rope classes,
135              you're now looking at four possibilities:  CString, the
136              libstdc++ string, the SGI string, and the SGI rope, and this
137              is all before any allocator or traits customizations!  (More
138              choices than you can shake a stick at -- want fries with that?)
139          </li>
140       </ul>
141    <p>Return <a href="#top">to top of page</a> or
142       <a href="../faq/index.html">to the FAQ</a>.
143    </p>
144
145 <hr />
146 <h2><a name="2">A case-insensitive string class</a></h2>
147    <p>The well-known-and-if-it-isn't-well-known-it-ought-to-be
148       <a href="http://www.peerdirect.com/resources/">Guru of the Week</a>
149       discussions held on Usenet covered this topic in January of 1998.
150       Briefly, the challenge was, &quot;write a 'ci_string' class which
151       is identical to the standard 'string' class, but is
152       case-insensitive in the same way as the (common but nonstandard)
153       C function stricmp():&quot;
154    </p>
155    <pre>
156    ci_string s( "AbCdE" );
157
158    // case insensitive
159    assert( s == "abcde" );
160    assert( s == "ABCDE" );
161
162    // still case-preserving, of course
163    assert( strcmp( s.c_str(), "AbCdE" ) == 0 );
164    assert( strcmp( s.c_str(), "abcde" ) != 0 ); </pre>
165
166    <p>The solution is surprisingly easy.  The original answer pages
167       on the GotW website were removed into cold storage, in
168       preparation for
169       <a href="http://cseng.aw.com/bookpage.taf?ISBN=0-201-61562-2">a
170       published book of GotW notes</a>.  Before being
171       put on the web, of course, it was posted on Usenet, and that
172       posting containing the answer is <a href="gotw29a.txt">available
173       here</a>.
174    </p>
175    <p>See?  Told you it was easy!</p>
176    <p><strong>Added June 2000:</strong>  The May issue of <u>C++ Report</u>
177       contains
178       a fascinating article by Matt Austern (yes, <em>the</em> Matt Austern)
179       on why case-insensitive comparisons are not as easy as they seem,
180       and why creating a class is the <em>wrong</em> way to go about it in
181       production code.  (The GotW answer mentions one of the principle
182       difficulties; his article mentions more.)
183    </p>
184    <p>Basically, this is &quot;easy&quot; only if you ignore some things,
185       things which may be too important to your program to ignore.  (I chose
186       to ignore them when originally writing this entry, and am surprised
187       that nobody ever called me on it...)  The GotW question and answer
188       remain useful instructional tools, however.
189    </p>
190    <p><strong>Added September 2000:</strong>  James Kanze provided a link to a
191       <a href="http://www.unicode.org/unicode/reports/tr21/">Unicode
192       Technical Report discussing case handling</a>, which provides some
193       very good information.
194    </p>
195    <p>Return <a href="#top">to top of page</a> or
196       <a href="../faq/index.html">to the FAQ</a>.
197    </p>
198
199 <hr />
200 <h2><a name="3">Breaking a C++ string into tokens</a></h2>
201    <p>The Standard C (and C++) function <code>strtok()</code> leaves a lot to
202       be desired in terms of user-friendliness.  It's unintuitive, it
203       destroys the character string on which it operates, and it requires
204       you to handle all the memory problems.  But it does let the client
205       code decide what to use to break the string into pieces; it allows
206       you to choose the &quot;whitespace,&quot; so to speak.
207    </p>
208    <p>A C++ implementation lets us keep the good things and fix those
209       annoyances.  The implementation here is more intuitive (you only
210       call it once, not in a loop with varying argument), it does not
211       affect the original string at all, and all the memory allocation
212       is handled for you.
213    </p>
214    <p>It's called stringtok, and it's a template function.  It's given
215       <a href="stringtok_h.txt">in this file</a> in a less-portable form than
216       it could be, to keep this example simple (for example, see the
217       comments on what kind of string it will accept).  The author uses
218       a more general (but less readable) form of it for parsing command
219       strings and the like.  If you compiled and ran this code using it:
220    </p>
221    <pre>
222    std::list&lt;string&gt;  ls;
223    stringtok (ls, " this  \t is\t\n  a test  ");
224    for (std::list&lt;string&gt;const_iterator i = ls.begin();
225         i != ls.end(); ++i)
226    {
227        std::cerr &lt;&lt; ':' &lt;&lt; (*i) &lt;&lt; ":\n";
228    } </pre>
229    <p>You would see this as output:
230    </p>
231    <pre>
232    :this:
233    :is:
234    :a:
235    :test: </pre>
236    <p>with all the whitespace removed.  The original <code>s</code> is still
237       available for use, <code>ls</code> will clean up after itself, and
238       <code>ls.size()</code> will return how many tokens there were.
239    </p>
240    <p>As always, there is a price paid here, in that stringtok is not
241       as fast as strtok.  The other benefits usually outweight that, however.
242       <a href="stringtok_std_h.txt">Another version of stringtok is given
243       here</a>, suggested by Chris King and tweaked by Petr Prikryl,
244       and this one uses the
245       transformation functions mentioned below.  If you are comfortable
246       with reading the new function names, this version is recommended
247       as an example.
248    </p>
249    <p><strong>Added February 2001:</strong>  Mark Wilden pointed out that the
250       standard <code>std::getline()</code> function can be used with standard
251       <a href="../27_io/howto.html">istringstreams</a> to perform
252       tokenizing as well.  Build an istringstream from the input text,
253       and then use std::getline with varying delimiters (the three-argument
254       signature) to extract tokens into a string.
255    </p>
256    <p>Return <a href="#top">to top of page</a> or
257       <a href="../faq/index.html">to the FAQ</a>.
258    </p>
259
260 <hr />
261 <h2><a name="4">Simple transformations</a></h2>
262    <p>Here are Standard, simple, and portable ways to perform common
263       transformations on a <code>string</code> instance, such as &quot;convert
264       to all upper case.&quot;  The word transformations is especially
265       apt, because the standard template function
266       <code>transform&lt;&gt;</code> is used.
267    </p>
268    <p>This code will go through some iterations (no pun).  Here's the
269       simplistic version usually seen on Usenet:
270    </p>
271    <pre>
272    #include &lt;string&gt;
273    #include &lt;algorithm&gt;
274    #include &lt;cctype&gt;      // old &lt;ctype.h&gt;
275
276    std::string  s ("Some Kind Of Initial Input Goes Here");
277
278    // Change everything into upper case
279    std::transform (s.begin(), s.end(), s.begin(), toupper);
280
281    // Change everything into lower case
282    std::transform (s.begin(), s.end(), s.begin(), tolower);
283
284    // Change everything back into upper case, but store the
285    // result in a different string
286    std::string  capital_s;
287    capital_s.reserve(s.size());
288    std::transform (s.begin(), s.end(), capital_s.begin(), tolower); </pre>
289    <p><span class="larger"><strong>Note</strong></span> that these calls all
290       involve the global C locale through the use of the C functions
291       <code>toupper/tolower</code>.  This is absolutely guaranteed to work --
292       but <em>only</em> if the string contains <em>only</em> characters
293       from the basic source character set, and there are <em>only</em>
294       96 of those.  Which means that not even all English text can be
295       represented (certain British spellings, proper names, and so forth).
296       So, if all your input forevermore consists of only those 96
297       characters (hahahahahaha), then you're done.
298    </p>
299    <p>At minimum, you can write short wrappers like
300    </p>
301    <pre>
302    char toLower (char c)
303    {
304       return tolower(static_cast&lt;unsigned char&gt;(c));
305    } </pre>
306    <p>The correct method is to use a facet for a particular locale
307       and call its conversion functions.  These are discussed more in
308       Chapter 22; the specific part is
309       <a href="../22_locale/howto.html#5">here</a>, which shows the
310       final version of this code.  (Thanks to James Kanze for assistance
311       and suggestions on all of this.)
312    </p>
313    <p>Another common operation is trimming off excess whitespace.  Much
314       like transformations, this task is trivial with the use of string's
315       <code>find</code> family.  These examples are broken into multiple
316       statements for readability:
317    </p>
318    <pre>
319    std::string  str (" \t blah blah blah    \n ");
320
321    // trim leading whitespace
322    string::size_type  notwhite = str.find_first_not_of(" \t\n");
323    str.erase(0,notwhite);
324
325    // trim trailing whitespace
326    notwhite = str.find_last_not_of(" \t\n"); 
327    str.erase(notwhite+1); </pre>
328    <p>Obviously, the calls to <code>find</code> could be inserted directly
329       into the calls to <code>erase</code>, in case your compiler does not
330       optimize named temporaries out of existence.
331    </p>
332    <p>Return <a href="#top">to top of page</a> or
333       <a href="../faq/index.html">to the FAQ</a>.
334    </p>
335
336 <hr />
337 <h2><a name="5">Making strings of arbitrary character types</a></h2>
338    <p>how to work with char_traits -- in the archives, just need to
339       go through and pull the examples together
340    </p>
341    <p>Return <a href="#top">to top of page</a> or
342       <a href="../faq/index.html">to the FAQ</a>.
343    </p>
344
345
346
347 <!-- ####################################################### -->
348
349 <hr />
350 <p class="fineprint"><em>
351 See <a href="../17_intro/license.html">license.html</a> for copying conditions.
352 Comments and suggestions are welcome, and may be sent to
353 <a href="mailto:libstdc++@gcc.gnu.org">the libstdc++ mailing list</a>.
354 </em></p>
355
356
357 </body>
358 </html>