Skip to main content

Section 5.4 Strings

Strings are sequential collections of zero or more characters such as letters, numbers and other symbols. There are actually two types of strings in C++ . The C++ string or just string from the <string> library is the more modern type, and it is very similar to the Python string class. The old style C-string which is essentially an array of char type. The char type itself is actually distinct from both types of strings.
char cppchar = 'a';   // char values use single quotes
string cppstring = "Hello World!";  // C++ strings use double quotes
char cstring[] = {"Hello World!"};    // C-string or char array uses double quotes
In older versions of C++, you must use a char array to work with filenames. In modern C++ (from C++11 onward), however, you can use a C++ string for everything. Since C++ strings are so much nicer and similar to Python strings, I would not recommend using C-strings.
Because strings are sequences, all of the typical sequence operations work as you would expect. In addition, the string library offers a huge number of methods, some of the most useful of which are shown in Table 5.4.1.
Table 5.4.1.
Method Name Use Explanation
[ ] astring[i] access value of character at index i
= astring[i]=value change value of character at index i
+ string1 + astring2 concatenate strings
append astring.append(string) Appends a string to the end of the string
push_back astring.push_back(char) Appends a character to the end of the string
pop_back astring.pop_back() Deletes the last character from the end of the string
insert astring.insert(i, string) Inserts a string at a specific index
erase astring.erase(i, j) Erases an element from one index to another
find astring.find(item) Returns the index of the first occurrence of item
size astring.size() Returns the size of the string
Check your understanding by completing the following question.

Reading Questions Reading Questions

1.

What is the correct definition of c-strings?
  • An array of characters that ends with a terminating null character. i.e. \0
  • Correct! a c-string is different from a string
  • A sequential data structure consisting of zero or more characters
  • Close, but that is the definition of a string, not a c-string
  • A data structure consisting of an ordered collection of data elements of identical type in which each element can be identified by an array index.
  • Sorry, thats not a string or a c-string
  • sequence container storing data of a single type that is stored in a dynamically allocated array which can change in size.
  • No, that’s a vector

2.

3.

4.

You have attempted 1 of 7 activities on this page.