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 4.

Table 4: String Methods Provided in C++
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) Append to string 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.

    Drag each data type to its' corresponding C++ initialization syntax. Feedback shows incorrect matches.
  • char
  • 'a'
  • char array
  • {'a'}
  • string
  • "a"
Next Section - 5.5. Hash Tables