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" />
13 <h1 class="centered"><a name="top">Chapter 21: Strings</a></h1>
15 <p>Chapter 21 deals with the C++ strings library (a welcome relief).
19 <!-- ####################################################### -->
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>
32 <!-- ####################################################### -->
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.
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:
47 <li>The Standard <code>string</code> supports all the operations
48 that CString does, with three exceptions.
50 <li>Two of those exceptions (whitespace trimming and case
51 conversion) are trivial to implement. In fact, we do so
54 <li>The third is <code>CString::Format</code>, which allows formatting
55 in the style of <code>sprintf</code>. This deserves some mention:
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:
68 #include <iostream>
69 #include <string>
70 #include <sstream>
72 string f (string& incoming) // incoming is "foo N"
74 istringstream incoming_stream(incoming);
78 incoming_stream >> the_word // extract "foo"
79 >> the_number; // extract N
81 ostringstream output_stream;
82 output_stream << "The word was " << the_word
83 << " and 3*N was " << (3*the_number);
85 return output_stream.str();
87 <p>A serious problem with CString is a design bug in its memory
88 allocation. Specifically, quoting from that same message:
91 CString suffers from a common programming error that results in
92 poor performance. Consider the following code:
94 CString n_copies_of (const CString& foo, unsigned n)
97 for (unsigned i = 0; i < n; i++)
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
109 If you replace CString with string in the above function, the
112 <p>Joe Buck also pointed out some other things to keep in mind when
113 comparing CString and the Standard string class:
116 <li>CString permits access to its internal representation; coders
117 who exploited that may have problems moving to <code>string</code>.
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>
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.
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<char></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?)
141 <p>Return <a href="#top">to top of page</a> or
142 <a href="../faq/index.html">to the FAQ</a>.
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, "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():"
156 ci_string s( "AbCdE" );
159 assert( s == "abcde" );
160 assert( s == "ABCDE" );
162 // still case-preserving, of course
163 assert( strcmp( s.c_str(), "AbCdE" ) == 0 );
164 assert( strcmp( s.c_str(), "abcde" ) != 0 ); </pre>
166 <p>The solution is surprisingly easy. The original answer pages
167 on the GotW website were removed into cold storage, in
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
175 <p>See? Told you it was easy!</p>
176 <p><strong>Added June 2000:</strong> The May issue of <u>C++ Report</u>
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.)
184 <p>Basically, this is "easy" 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.
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.
195 <p>Return <a href="#top">to top of page</a> or
196 <a href="../faq/index.html">to the FAQ</a>.
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 "whitespace," so to speak.
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
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:
222 std::list<string> ls;
223 stringtok (ls, " this \t is\t\n a test ");
224 for (std::list<string>const_iterator i = ls.begin();
227 std::cerr << ':' << (*i) << ":\n";
229 <p>You would see this as output:
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.
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
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.
256 <p>Return <a href="#top">to top of page</a> or
257 <a href="../faq/index.html">to the FAQ</a>.
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 "convert
264 to all upper case." The word transformations is especially
265 apt, because the standard template function
266 <code>transform<></code> is used.
268 <p>This code will go through some iterations (no pun). Here's the
269 simplistic version usually seen on Usenet:
272 #include <string>
273 #include <algorithm>
274 #include <cctype> // old <ctype.h>
276 std::string s ("Some Kind Of Initial Input Goes Here");
278 // Change everything into upper case
279 std::transform (s.begin(), s.end(), s.begin(), toupper);
281 // Change everything into lower case
282 std::transform (s.begin(), s.end(), s.begin(), tolower);
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.
299 <p>At minimum, you can write short wrappers like
302 char toLower (char c)
304 return tolower(static_cast<unsigned char>(c));
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.)
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:
319 std::string str (" \t blah blah blah \n ");
321 // trim leading whitespace
322 string::size_type notwhite = str.find_first_not_of(" \t\n");
323 str.erase(0,notwhite);
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.
332 <p>Return <a href="#top">to top of page</a> or
333 <a href="../faq/index.html">to the FAQ</a>.
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
341 <p>Return <a href="#top">to top of page</a> or
342 <a href="../faq/index.html">to the FAQ</a>.
347 <!-- ####################################################### -->
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>.