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