]> gcc.gnu.org Git - gcc.git/blob - libstdc++-v3/doc/xml/manual/strings.xml
[multiple changes]
[gcc.git] / libstdc++-v3 / doc / xml / manual / strings.xml
1 <?xml version='1.0'?>
2 <!DOCTYPE part PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN"
3 "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd"
4 [ ]>
5
6 <part id="manual.strings" xreflabel="Strings">
7 <?dbhtml filename="strings.html"?>
8
9 <partinfo>
10 <keywordset>
11 <keyword>
12 ISO C++
13 </keyword>
14 <keyword>
15 library
16 </keyword>
17 </keywordset>
18 </partinfo>
19
20 <title>Strings</title>
21
22 <!-- Chapter 01 : Character Traits -->
23
24 <!-- Chapter 02 : String Classes -->
25 <chapter id="manual.strings.string" xreflabel="string">
26 <title>String Classes</title>
27
28 <sect1 id="strings.string.simple" xreflabel="Simple Transformations">
29 <title>Simple Transformations</title>
30 <para>
31 Here are Standard, simple, and portable ways to perform common
32 transformations on a <code>string</code> instance, such as
33 &quot;convert to all upper case.&quot; The word transformations
34 is especially apt, because the standard template function
35 <code>transform&lt;&gt;</code> is used.
36 </para>
37 <para>
38 This code will go through some iterations. Here's a simple
39 version:
40 </para>
41 <programlisting>
42 #include &lt;string&gt;
43 #include &lt;algorithm&gt;
44 #include &lt;cctype&gt; // old &lt;ctype.h&gt;
45
46 struct ToLower
47 {
48 char operator() (char c) const { return std::tolower(c); }
49 };
50
51 struct ToUpper
52 {
53 char operator() (char c) const { return std::toupper(c); }
54 };
55
56 int main()
57 {
58 std::string s ("Some Kind Of Initial Input Goes Here");
59
60 // Change everything into upper case
61 std::transform (s.begin(), s.end(), s.begin(), ToUpper());
62
63 // Change everything into lower case
64 std::transform (s.begin(), s.end(), s.begin(), ToLower());
65
66 // Change everything back into upper case, but store the
67 // result in a different string
68 std::string capital_s;
69 capital_s.resize(s.size());
70 std::transform (s.begin(), s.end(), capital_s.begin(), ToUpper());
71 }
72 </programlisting>
73 <para>
74 <emphasis>Note</emphasis> that these calls all
75 involve the global C locale through the use of the C functions
76 <code>toupper/tolower</code>. This is absolutely guaranteed to work --
77 but <emphasis>only</emphasis> if the string contains <emphasis>only</emphasis> characters
78 from the basic source character set, and there are <emphasis>only</emphasis>
79 96 of those. Which means that not even all English text can be
80 represented (certain British spellings, proper names, and so forth).
81 So, if all your input forevermore consists of only those 96
82 characters (hahahahahaha), then you're done.
83 </para>
84 <para><emphasis>Note</emphasis> that the
85 <code>ToUpper</code> and <code>ToLower</code> function objects
86 are needed because <code>toupper</code> and <code>tolower</code>
87 are overloaded names (declared in <code>&lt;cctype&gt;</code> and
88 <code>&lt;locale&gt;</code>) so the template-arguments for
89 <code>transform&lt;&gt;</code> cannot be deduced, as explained in
90 <ulink url="http://gcc.gnu.org/ml/libstdc++/2002-11/msg00180.html">this
91 message</ulink>.
92 <!-- section 14.8.2.4 clause 16 in ISO 14882:1998 -->
93 At minimum, you can write short wrappers like
94 </para>
95 <programlisting>
96 char toLower (char c)
97 {
98 return std::tolower(c);
99 } </programlisting>
100 <para>The correct method is to use a facet for a particular locale
101 and call its conversion functions. These are discussed more in
102 Chapter 22; the specific part is
103 <ulink url="../22_locale/howto.html#7">Correct Transformations</ulink>,
104 which shows the final version of this code. (Thanks to James Kanze
105 for assistance and suggestions on all of this.)
106 </para>
107 <para>Another common operation is trimming off excess whitespace. Much
108 like transformations, this task is trivial with the use of string's
109 <code>find</code> family. These examples are broken into multiple
110 statements for readability:
111 </para>
112 <programlisting>
113 std::string str (" \t blah blah blah \n ");
114
115 // trim leading whitespace
116 string::size_type notwhite = str.find_first_not_of(" \t\n");
117 str.erase(0,notwhite);
118
119 // trim trailing whitespace
120 notwhite = str.find_last_not_of(" \t\n");
121 str.erase(notwhite+1); </programlisting>
122 <para>Obviously, the calls to <code>find</code> could be inserted directly
123 into the calls to <code>erase</code>, in case your compiler does not
124 optimize named temporaries out of existence.
125 </para>
126
127 </sect1>
128 <sect1 id="strings.string.case" xreflabel="Case Sensitivity">
129 <title>Case Sensitivity</title>
130 <para>
131 </para>
132
133 <para>The well-known-and-if-it-isn't-well-known-it-ought-to-be
134 <ulink url="http://www.gotw.ca/gotw/">Guru of the Week</ulink>
135 discussions held on Usenet covered this topic in January of 1998.
136 Briefly, the challenge was, <quote>write a 'ci_string' class which
137 is identical to the standard 'string' class, but is
138 case-insensitive in the same way as the (common but nonstandard)
139 C function stricmp()</quote>.
140 </para>
141 <programlisting>
142 ci_string s( "AbCdE" );
143
144 // case insensitive
145 assert( s == "abcde" );
146 assert( s == "ABCDE" );
147
148 // still case-preserving, of course
149 assert( strcmp( s.c_str(), "AbCdE" ) == 0 );
150 assert( strcmp( s.c_str(), "abcde" ) != 0 ); </programlisting>
151
152 <para>The solution is surprisingly easy. The original answer was
153 posted on Usenet, and a revised version appears in Herb Sutter's
154 book <emphasis>Exceptional C++</emphasis> and on his website as <ulink url="http://www.gotw.ca/gotw/029.htm">GotW 29</ulink>.
155 </para>
156 <para>See? Told you it was easy!</para>
157 <para>
158 <emphasis>Added June 2000:</emphasis> The May 2000 issue of C++
159 Report contains a fascinating <ulink
160 url="http://lafstern.org/matt/col2_new.pdf"> article</ulink> by
161 Matt Austern (yes, <emphasis>the</emphasis> Matt Austern) on why
162 case-insensitive comparisons are not as easy as they seem, and
163 why creating a class is the <emphasis>wrong</emphasis> way to go
164 about it in production code. (The GotW answer mentions one of
165 the principle difficulties; his article mentions more.)
166 </para>
167 <para>Basically, this is &quot;easy&quot; only if you ignore some things,
168 things which may be too important to your program to ignore. (I chose
169 to ignore them when originally writing this entry, and am surprised
170 that nobody ever called me on it...) The GotW question and answer
171 remain useful instructional tools, however.
172 </para>
173 <para><emphasis>Added September 2000:</emphasis> James Kanze provided a link to a
174 <ulink url="http://www.unicode.org/unicode/reports/tr21/">Unicode
175 Technical Report discussing case handling</ulink>, which provides some
176 very good information.
177 </para>
178
179 </sect1>
180 <sect1 id="strings.string.character_types" xreflabel="Arbitrary Characters">
181 <title>Arbitrary Character Types</title>
182 <para>
183 </para>
184
185 <para>The <code>std::basic_string</code> is tantalizingly general, in that
186 it is parameterized on the type of the characters which it holds.
187 In theory, you could whip up a Unicode character class and instantiate
188 <code>std::basic_string&lt;my_unicode_char&gt;</code>, or assuming
189 that integers are wider than characters on your platform, maybe just
190 declare variables of type <code>std::basic_string&lt;int&gt;</code>.
191 </para>
192 <para>That's the theory. Remember however that basic_string has additional
193 type parameters, which take default arguments based on the character
194 type (called <code>CharT</code> here):
195 </para>
196 <programlisting>
197 template &lt;typename CharT,
198 typename Traits = char_traits&lt;CharT&gt;,
199 typename Alloc = allocator&lt;CharT&gt; &gt;
200 class basic_string { .... };</programlisting>
201 <para>Now, <code>allocator&lt;CharT&gt;</code> will probably Do The Right
202 Thing by default, unless you need to implement your own allocator
203 for your characters.
204 </para>
205 <para>But <code>char_traits</code> takes more work. The char_traits
206 template is <emphasis>declared</emphasis> but not <emphasis>defined</emphasis>.
207 That means there is only
208 </para>
209 <programlisting>
210 template &lt;typename CharT&gt;
211 struct char_traits
212 {
213 static void foo (type1 x, type2 y);
214 ...
215 };</programlisting>
216 <para>and functions such as char_traits&lt;CharT&gt;::foo() are not
217 actually defined anywhere for the general case. The C++ standard
218 permits this, because writing such a definition to fit all possible
219 CharT's cannot be done.
220 </para>
221 <para>The C++ standard also requires that char_traits be specialized for
222 instantiations of <code>char</code> and <code>wchar_t</code>, and it
223 is these template specializations that permit entities like
224 <code>basic_string&lt;char,char_traits&lt;char&gt;&gt;</code> to work.
225 </para>
226 <para>If you want to use character types other than char and wchar_t,
227 such as <code>unsigned char</code> and <code>int</code>, you will
228 need suitable specializations for them. For a time, in earlier
229 versions of GCC, there was a mostly-correct implementation that
230 let programmers be lazy but it broke under many situations, so it
231 was removed. GCC 3.4 introduced a new implementation that mostly
232 works and can be specialized even for <code>int</code> and other
233 built-in types.
234 </para>
235 <para>If you want to use your own special character class, then you have
236 <ulink url="http://gcc.gnu.org/ml/libstdc++/2002-08/msg00163.html">a lot
237 of work to do</ulink>, especially if you with to use i18n features
238 (facets require traits information but don't have a traits argument).
239 </para>
240 <para>Another example of how to specialize char_traits was given <ulink url="http://gcc.gnu.org/ml/libstdc++/2002-08/msg00260.html">on the
241 mailing list</ulink> and at a later date was put into the file <code>
242 include/ext/pod_char_traits.h</code>. We agree
243 that the way it's used with basic_string (scroll down to main())
244 doesn't look nice, but that's because <ulink url="http://gcc.gnu.org/ml/libstdc++/2002-08/msg00236.html">the
245 nice-looking first attempt</ulink> turned out to <ulink url="http://gcc.gnu.org/ml/libstdc++/2002-08/msg00242.html">not
246 be conforming C++</ulink>, due to the rule that CharT must be a POD.
247 (See how tricky this is?)
248 </para>
249
250 </sect1>
251
252 <sect1 id="strings.string.token" xreflabel="Tokenizing">
253 <title>Tokenizing</title>
254 <para>
255 </para>
256 <para>The Standard C (and C++) function <code>strtok()</code> leaves a lot to
257 be desired in terms of user-friendliness. It's unintuitive, it
258 destroys the character string on which it operates, and it requires
259 you to handle all the memory problems. But it does let the client
260 code decide what to use to break the string into pieces; it allows
261 you to choose the &quot;whitespace,&quot; so to speak.
262 </para>
263 <para>A C++ implementation lets us keep the good things and fix those
264 annoyances. The implementation here is more intuitive (you only
265 call it once, not in a loop with varying argument), it does not
266 affect the original string at all, and all the memory allocation
267 is handled for you.
268 </para>
269 <para>It's called stringtok, and it's a template function. Sources are
270 as below, in a less-portable form than it could be, to keep this
271 example simple (for example, see the comments on what kind of
272 string it will accept).
273 </para>
274
275 <programlisting>
276 #include &lt;string&gt;
277 template &lt;typename Container&gt;
278 void
279 stringtok(Container &amp;container, string const &amp;in,
280 const char * const delimiters = " \t\n")
281 {
282 const string::size_type len = in.length();
283 string::size_type i = 0;
284
285 while (i &lt; len)
286 {
287 // Eat leading whitespace
288 i = in.find_first_not_of(delimiters, i);
289 if (i == string::npos)
290 return; // Nothing left but white space
291
292 // Find the end of the token
293 string::size_type j = in.find_first_of(delimiters, i);
294
295 // Push token
296 if (j == string::npos)
297 {
298 container.push_back(in.substr(i));
299 return;
300 }
301 else
302 container.push_back(in.substr(i, j-i));
303
304 // Set up for next loop
305 i = j + 1;
306 }
307 }
308 </programlisting>
309
310
311 <para>
312 The author uses a more general (but less readable) form of it for
313 parsing command strings and the like. If you compiled and ran this
314 code using it:
315 </para>
316
317
318 <programlisting>
319 std::list&lt;string&gt; ls;
320 stringtok (ls, " this \t is\t\n a test ");
321 for (std::list&lt;string&gt;const_iterator i = ls.begin();
322 i != ls.end(); ++i)
323 {
324 std::cerr &lt;&lt; ':' &lt;&lt; (*i) &lt;&lt; ":\n";
325 } </programlisting>
326 <para>You would see this as output:
327 </para>
328 <programlisting>
329 :this:
330 :is:
331 :a:
332 :test: </programlisting>
333 <para>with all the whitespace removed. The original <code>s</code> is still
334 available for use, <code>ls</code> will clean up after itself, and
335 <code>ls.size()</code> will return how many tokens there were.
336 </para>
337 <para>As always, there is a price paid here, in that stringtok is not
338 as fast as strtok. The other benefits usually outweigh that, however.
339 <ulink url="stringtok_std_h.txt">Another version of stringtok is given
340 here</ulink>, suggested by Chris King and tweaked by Petr Prikryl,
341 and this one uses the
342 transformation functions mentioned below. If you are comfortable
343 with reading the new function names, this version is recommended
344 as an example.
345 </para>
346 <para><emphasis>Added February 2001:</emphasis> Mark Wilden pointed out that the
347 standard <code>std::getline()</code> function can be used with standard
348 <ulink url="../27_io/howto.html">istringstreams</ulink> to perform
349 tokenizing as well. Build an istringstream from the input text,
350 and then use std::getline with varying delimiters (the three-argument
351 signature) to extract tokens into a string.
352 </para>
353
354
355 </sect1>
356 <sect1 id="strings.string.shrink" xreflabel="Shrink to Fit">
357 <title>Shrink to Fit</title>
358 <para>
359 </para>
360 <para>From GCC 3.4 calling <code>s.reserve(res)</code> on a
361 <code>string s</code> with <code>res &lt; s.capacity()</code> will
362 reduce the string's capacity to <code>std::max(s.size(), res)</code>.
363 </para>
364 <para>This behaviour is suggested, but not required by the standard. Prior
365 to GCC 3.4 the following alternative can be used instead
366 </para>
367 <programlisting>
368 std::string(str.data(), str.size()).swap(str);
369 </programlisting>
370 <para>This is similar to the idiom for reducing a <code>vector</code>'s
371 memory usage (see <ulink url='../faq/index.html#5_9'>FAQ 5.9</ulink>) but
372 the regular copy constructor cannot be used because libstdc++'s
373 <code>string</code> is Copy-On-Write.
374 </para>
375
376
377 </sect1>
378
379 <sect1 id="strings.string.Cstring" xreflabel="CString (MFC)">
380 <title>CString (MFC)</title>
381 <para>
382 </para>
383
384 <para>A common lament seen in various newsgroups deals with the Standard
385 string class as opposed to the Microsoft Foundation Class called
386 CString. Often programmers realize that a standard portable
387 answer is better than a proprietary nonportable one, but in porting
388 their application from a Win32 platform, they discover that they
389 are relying on special functions offered by the CString class.
390 </para>
391 <para>Things are not as bad as they seem. In
392 <ulink url="http://gcc.gnu.org/ml/gcc/1999-04n/msg00236.html">this
393 message</ulink>, Joe Buck points out a few very important things:
394 </para>
395 <itemizedlist>
396 <listitem><para>The Standard <code>string</code> supports all the operations
397 that CString does, with three exceptions.
398 </para></listitem>
399 <listitem><para>Two of those exceptions (whitespace trimming and case
400 conversion) are trivial to implement. In fact, we do so
401 on this page.
402 </para></listitem>
403 <listitem><para>The third is <code>CString::Format</code>, which allows formatting
404 in the style of <code>sprintf</code>. This deserves some mention:
405 </para></listitem>
406 </itemizedlist>
407 <para>
408 The old libg++ library had a function called form(), which did much
409 the same thing. But for a Standard solution, you should use the
410 stringstream classes. These are the bridge between the iostream
411 hierarchy and the string class, and they operate with regular
412 streams seamlessly because they inherit from the iostream
413 hierarchy. An quick example:
414 </para>
415 <programlisting>
416 #include &lt;iostream&gt;
417 #include &lt;string&gt;
418 #include &lt;sstream&gt;
419
420 string f (string&amp; incoming) // incoming is "foo N"
421 {
422 istringstream incoming_stream(incoming);
423 string the_word;
424 int the_number;
425
426 incoming_stream &gt;&gt; the_word // extract "foo"
427 &gt;&gt; the_number; // extract N
428
429 ostringstream output_stream;
430 output_stream &lt;&lt; "The word was " &lt;&lt; the_word
431 &lt;&lt; " and 3*N was " &lt;&lt; (3*the_number);
432
433 return output_stream.str();
434 } </programlisting>
435 <para>A serious problem with CString is a design bug in its memory
436 allocation. Specifically, quoting from that same message:
437 </para>
438 <programlisting>
439 CString suffers from a common programming error that results in
440 poor performance. Consider the following code:
441
442 CString n_copies_of (const CString&amp; foo, unsigned n)
443 {
444 CString tmp;
445 for (unsigned i = 0; i &lt; n; i++)
446 tmp += foo;
447 return tmp;
448 }
449
450 This function is O(n^2), not O(n). The reason is that each +=
451 causes a reallocation and copy of the existing string. Microsoft
452 applications are full of this kind of thing (quadratic performance
453 on tasks that can be done in linear time) -- on the other hand,
454 we should be thankful, as it's created such a big market for high-end
455 ix86 hardware. :-)
456
457 If you replace CString with string in the above function, the
458 performance is O(n).
459 </programlisting>
460 <para>Joe Buck also pointed out some other things to keep in mind when
461 comparing CString and the Standard string class:
462 </para>
463 <itemizedlist>
464 <listitem><para>CString permits access to its internal representation; coders
465 who exploited that may have problems moving to <code>string</code>.
466 </para></listitem>
467 <listitem><para>Microsoft ships the source to CString (in the files
468 MFC\SRC\Str{core,ex}.cpp), so you could fix the allocation
469 bug and rebuild your MFC libraries.
470 <emphasis><emphasis>Note:</emphasis> It looks like the CString shipped
471 with VC++6.0 has fixed this, although it may in fact have been
472 one of the VC++ SPs that did it.</emphasis>
473 </para></listitem>
474 <listitem><para><code>string</code> operations like this have O(n) complexity
475 <emphasis>if the implementors do it correctly</emphasis>. The libstdc++
476 implementors did it correctly. Other vendors might not.
477 </para></listitem>
478 <listitem><para>While parts of the SGI STL are used in libstdc++, their
479 string class is not. The SGI <code>string</code> is essentially
480 <code>vector&lt;char&gt;</code> and does not do any reference
481 counting like libstdc++'s does. (It is O(n), though.)
482 So if you're thinking about SGI's string or rope classes,
483 you're now looking at four possibilities: CString, the
484 libstdc++ string, the SGI string, and the SGI rope, and this
485 is all before any allocator or traits customizations! (More
486 choices than you can shake a stick at -- want fries with that?)
487 </para></listitem>
488 </itemizedlist>
489
490 </sect1>
491 </chapter>
492
493 <!-- Chapter 03 : Interacting with C -->
494
495 </part>
This page took 0.063681 seconds and 5 git commands to generate.