ArticleslgStudy

computer science

C++ string handling

C++ string handling is a computer science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand C++ string handling rather than just read about it. In short: The C++ programming language has support for string handling, mostly implemented in its standard library. The language standard specifies several string types, some inherited from C, some designed to make use of the language's features, such as classes and RAII.

Key takeaways

  • C++ string handling belongs to computer science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect C++ string handling to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of C++ string handling from memory before moving on to harder problems.

Reference excerpt

The C++ programming language has support for string handling, mostly implemented in its standard library. The language standard specifies several string types, some inherited from C, some designed to make use of the language's features, such as classes and RAII. The most-used of these is std::string, while std::string_view is used for non-owning string views. Since the initial versions of C++ had only the "low-level" C string handling functionality and conventions, multiple incompatible designs for string handling classes have been designed over the years and are still used instead of std::string, and C++ programmers may need to handle multiple conventions in a single application.

History The std::string type is the main string datatype in standard C++ since 1998, but it was not always part of C++. From C, C++ inherited the convention of using null-terminated strings that are handled by a pointer to their first element, and a library of functions that manipulate such strings. In modern standard C++, a string literal such as "hello" still denotes a NUL-terminated array of characters. Using C++ classes to implement a string type offers several benefits of automated memory management and a reduced risk of out-of-bounds accesses, and more intuitive syntax for string comparison and concatenation. Therefore, it was strongly tempting to create such a class. Over the years, C++ application, library and framework developers produced their own, incompatible string representations, such as the one in AT&T's Standard Components library (the first such implementation, 1983) or the CString type in Microsoft's MFC or the QString in Qt. The various vendors' string types have different implementation strategies and performance characteristics, which made conversion of code and even assignment from one to another difficult:

Some used a copy-on-write strategy with major performance implications (making some operations much faster and some much slower). Though most agreed on syntax for comparison, assignment, and concatenation; the syntax to extract substrings or perform searches varied widely. Not everything was Unicode, leading to widespread variations in how or if encoding was stored and when translation was done, and sometimes very expensive assignment operators. It was also believed code units larger than bytes were necessary to support Unicode, leading to string types that could not interoperate in any efficient manner. While std::string standardized strings, legacy applications still commonly contain such custom string types and libraries may expect C-style strings, making it "virtually impossible" to avoid using multiple string types in C++ programs and requiring programmers to decide on the desired string representation ahead of starting a project. In a 1991 retrospective on the history of C++, its inventor Bjarne Stroustrup called the lack of a standard string type (and some other standard types) in C++ 1.0 the worst mistake he made in its development; "the absence of those led to everybody re-inventing the wheel and to an unnecessary diversity in the most fundamental classes".

Description The std::string class is the standard representation for a text string since C++98. The class provides some typical string operations like comparison, concatenation, find and replace, and a function for obtaining substrings. A std::string can be constructed from a C-style string, and a C-style string can also be obtained from one. The individual units making up the string are of type char (a single byte). In modern usage these are often not "characters", but parts of a multibyte character encoding such as UTF-8.

Copy on Write A copy-on-write implementation means

does not actually copy the content of a to b; instead, both strings share their contents and a reference count on the content is incremented. The actual copying is postponed until a mutating operation, such as changing a character, makes the strings' contents differ. The copy-on-write strategy was deliberately allowed by the initial C++ Standard for std::string because it was deemed a useful optimization, and used by nearly all implementations. However, there were mistakes, in particular the operator[] returned a non-const reference in order to make it easy to port C code such as s[5] = 'a';, and had to trigger a copy. Multi-threading caused optimizations (such as not copying when the reference count is one) to fail and on modern processors the necessary locking to examine or change the reference count is more expensive than copying a small string. This caused implementations, first MSVC and later GCC, to move away from copy-on-write. The optimization was finally disallowed in C++11. Most implementations now do small string optimization (SSO), where strings less than 16 (or 23) bytes long are stored in the string object and no buffer is allocated. This is significantly faster than reference counting as many strings are this small, and buffer allocation is extremely expensive compared to copying local blocks of memory.

String views Unlike in other languages, such as Java java.lang.String or C# System.String, C++ strings are always mutable, as quoted null-terminated string constants served most of the purpose of a non-mutable class. C++ requires that the following code make a copy of the string, this is quite slow compared to passing a pointer, even if copy on write reference counts are used.

Though the compiler could optimize this away for inline functions, few relied on this and almost always strings are passed as a const reference: Conversion from a string constant also required constructing a temporary std::string and was slow, usually leading to overloaded functions:

The C++17 standard adds the std::string_view class that is only a pointer and length to read-only data, and is a drop-in replacement for an immutable temporary std::string and makes pass-by-value arguments faster than either of the above examples:

All functions in a library that take a string argument must be rewritten to take advantage of this in C++17, as conversion from std::string_view to std::string is still expensive.

Other code units std::string is a typedef for a particular instantiation of the std::basic_string<CharT, Traits, Alloc> template class. Its definition is found in the <string> header:

… excerpt ends here. Continue reading the full article.

Worked examples

Example 1 — a first encounter with C++ string handling

Start with the simplest possible case. Write down what C++ string handling claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In computer science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to C++ string handling before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about C++ string handling ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of C++ string handling

In research
C++ string handling appears in computer science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses C++ string handling in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
C++ string handling is common in secondary-school and first-year university syllabi. It links to neighbouring topics C++, C++ Standard Library, String (computer science), so understanding it makes those chapters shorter.
In everyday life
Look for C++ string handling outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “C++ string handling” →

How to study C++ string handling in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what C++ string handling means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain C++ string handling out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is C++ string handling in simple terms?

The C++ programming language has support for string handling, mostly implemented in its standard library. The language standard specifies several string types, some inherited from C, some designed to make use of the language's features, such as classes and RAII.

Why does C++ string handling matter?

Because it connects several computer science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study C++ string handling?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on C++ string handling.

Tags

  • C++
  • C++ Standard Library
  • String (computer science)

Keep exploring