The C++ String Library

Table of Contents


A string is a special data type that really is just an array of char variables. A string has a lot going on behind-the-scenes, and it also has a set of functions you can use to do some common operations on a string - finding text, getting a letter at some position, and more.

Note that everything with strings is case-sensitive. A computer considers the letter 'a' and 'A' different, since they are represented by different number codes. Keep that in mind for each of the string's functions.

1. Strings as arrays

When we declare a string like this:

string str = "pizza";

what we have behind-the-scenes is an array like this:

Value: 'p' 'i' 'z' 'z' 'a'
Index: 0 1 2 3 4

Declaring a string actually gives us an array of *char variables*. We can access the string as a whole by using the string variable's name (str), or access one char at a time by treating str like an array.

1.1. Subscript operator - get one char with [ ]

We can access each letter of the string directly with the subscript operator, just like an array:

cout << str[0] << endl; // Outputs p
cout << str[1] << endl; // Outputs i
cout << str[2] << endl; // Outputs z
cout << str[3] << endl; // Outputs z
cout << str[4] << endl; // Outputs a

Because we can act on a string like an array, this means we can also use a variable to access an arbitrary index of a character in the array…

int i;
cout << "Get which letter? ";
cin >> i;
cout << str[i];

Or even iterate over the string with a for loop

for ( int i = 0; i < str.size(); i++ )
    cout << i << " = " << str[i] << endl;

Additionally, strings have a set of functions that we can use to manipulate, search, and otherwise work with them.

2. String functionality

2.1. Size of the string

size_t size() const;

The string's size() function will return the size of the string - how many characters are stored in the string. The size_t data type is just a type of integer - an unsigned integer, because sizes cannot be negative amounts.


Example: Outputting a string's length
Let's write a little program that asks the user to enter some text, and then outputs the length of the string:
string text;
cout << "Enter some text: ";
getline( cin, text );
cout << "That string is " << text.size()
    << " characters long!" << endl;

When the user enters a line of text, it will count all characters (including spaces) in the string, so the text "cats dogs" would be 9 characters long.

Enter some text: cats dogs
That string is 9 characters long!


Example: Counting z's
If we wanted to use a for loop to iterate over all the letters of an array, we could! Perhaps we want to count the amount of z's that show up:
string text;
int zCount = 0;

cout << "Enter some text: ";
getline( cin, text );

// Iterate from i=0 to the size of the string (not-inclusive)
for ( unsigned int i = 0; i < text.size(); i++ )
    // If this letter is a lower-case z or upper-case Z
    if ( text[i] == 'z' || text[i] == 'Z' )
        // Add one to z count

// Display the result
cout << "There were " << zCount
    << " z(s) in the string!" << endl;
Enter some text: The wizard fought a zombie lizard
There were 3 z(s) in the string!


2.2. Concatenating strings with +

We can use the + operator to add strings together as well. This is called concatenation.

Let's say we have two strings we want to combine - favoriteColor and petName, we can use the concatenation operator + to build a new string, superSecurePassword.

string favoriteColor = "purple";
string petName = "Luna";
string superSecurePassword = favoriteColor + petName;
cout << superSecurePassword << endl; // = purpleLuna


We can also add onto strings by using the += operator. Let's say you're building a string over time in a program, and want to append parts separately.

string pizzaToppings = "";

// Later on...
pizzaToppings += "Buffalo sauce, ";

// Later on...
pizzaToppings += "Cheese, ";

// Later on...
pizzaToppings += "Pineapple";

// Later on...
cout << pizzaToppings << endl;

At the end of the program, the value of pizzaToppings would be:

"Buffalo sauce, Cheese, Pineapple"

2.3. Finding text with find()

size_t find (const string& str, size_t pos = 0 ) const;

The find function can be used to look for a substring in a bigger string. If the substring is found, its position is returned. Otherwise, the value of string::npos is found.

When a starting pos is included, it only begins the search at that position. If left off, it defaults to 0 (the start of the string).


So when we want to search a string for some text, we can call it like bigString.find( findMeString ), and that function call will return an unsigned integer: the location of the findMeString within bigString, or the value of string::npos when it is not found.

string str = "this was written during the 2021 winter storm make it stop please.";

string findMe = "winter";

size_t position = str.find( findMe );

cout << "The text \"" << findMe
    << "\" was found at position " << position << endl;
The text "winter" was found at position 33

2.4. Finding substrings with substr()

string substr (size_t pos = 0, size_t len = npos) const;

Returns a string within the string, starting at the position pos provided, and with a length of len.


With the substr() function, we can pull part of a string out, using a starting point and a length.

string text = "Name: Bob";

int start = 6;
int length = 3;

string name = text.substr( start, length );

cout << "Extracted \"" << name << "\"." << endl;

Extracted "Bob".


2.5. Comparing text with compare()

int compare (const string& str) const;

This compares the string with str and returns an integer:

  • \(0\) is returned if both strings are the same.
  • \(< 1\) (a negative number) is returned if the caller string is "less-than" the str string.
  • \(> 1\) (a positive number) is returned if the caller string is "greater-than" the str string.

One character is "less than" another if it comes before, and it is "greater than" if it comes after, alphabetically.

(Remember that lower-case and upper-case letters are considered separate, so comparing 'a' to 'A' would actually return a positive number.)


string first;
string second;

cout << "Enter first string: ";
cin >> first;

cout << "Enter second string: ";
cin >> second;

int order = second );

cout << endl << "Result: " << order << endl;
Enter first string: apple
Enter second string: banana

Result: -1


2.6. Inserting text into a string with insert()

= string& insert (sizet pos, const string& str);=

This function will take the calling string and modify it by inserting the string str at the position pos.


string text = "helloworld";

cout << "Original text: " << text << endl;

int start;
string insertText;

cout << "Enter text to insert: ";
getline( cin, insertText );

cout << "Enter position to insert: ";
cin >> start;

text = text.insert( start, insertText );

cout << endl << "String is now: " << text << endl;
Original text: helloworld
Enter text to insert: -to the-
Enter position to insert: 5

String is now: hello-to the-world

2.7. Erasing a chunk of text with erase()

string& erase (size_t pos = 0, size_t len = npos);

This function will return a string with a portion erased, starting at position pos and pulling out a length of len.


string text = "helloworld";

cout << "Original text: " << text << endl;

int start;
int length;

cout << "Enter position to begin erasing: ";
cin >> start;

cout << "Enter length of text to erase: ";
cin >> length;

text = text.erase( start, length );
cout << endl << "String is now: " << text << endl;
Original text: helloworld
Enter position to begin erasing: 2
Enter length of text to erase: 5

String is now: herld

2.8. Replacing a region of text with replace()

string& replace (size_t pos, size_t len, const string& str);

This function is similar to erase, except it will insert the string str in place of the erased text.


string text = "helloworld";

cout << "Original text: " << text << endl;

int start;
int length;
string replaceWith;

cout << "Enter string to replace with: ";
getline( cin, replaceWith );

cout << "Enter position to begin replacing: ";
cin >> start;

cout << "Enter length of text to replacing: ";
cin >> length;

text = text.replace( start, length, replaceWith );
cout << endl << "String is now: " << text << endl;
Original text: helloworld
Enter string to replace with: BYE
Enter position to begin replacing: 2
Enter length of text to replacing: 5

String is now: heBYErld

Author: Rachel Wil Sha Singh

Created: 2023-10-21 Sat 23:24