C++ Strings

A C++ string is a value that stores text, such as a name, word, or sentence. The most common beginner-friendly string type is std::string, which comes from the <string> header.

Unlike a single char, which stores one character, a std::string can store many characters and provides useful operations for working with text.

Creating Strings

To use std::string, include <string>. You can create a string variable, assign text to it, and print it with std::cout.

#include <iostream>
#include <string>

int main(void) {
    std::string language = "C++";
    std::string message = "Strings store text.";

    std::cout << language << std::endl;
    std::cout << message << std::endl;

    return 0;
}

Output:

C++
Strings store text.

The text inside double quotes is called a string literal. C++ copies that text into the language and message variables.

Joining Strings

You can join strings with the + operator. This is called concatenation. If you want spaces or punctuation in the final text, include them in one of the strings.

#include <iostream>
#include <string>

int main(void) {
    std::string first = "Ada";
    std::string last = "Lovelace";
    std::string fullName = first + " " + last;

    std::cout << "Full name: " << fullName << std::endl;

    return 0;
}

Output:

Full name: Ada Lovelace

The expression first + " " + last creates a new string containing the first name, a space, and the last name.

String Length

The length() function returns how many characters are in a string. The similar size() function gives the same result for std::string.

#include <iostream>
#include <string>

int main(void) {
    std::string word = "keyboard";

    std::cout << "Word: " << word << std::endl;
    std::cout << "Length: " << word.length() << std::endl;

    return 0;
}

Output:

Word: keyboard
Length: 8

Spaces and punctuation count as characters too. For example, "Hi!" has a length of 3.

Accessing Characters

Each character in a string has an index. Indexes start at 0, so the first character is at index 0, the second is at index 1, and so on.

#include <iostream>
#include <string>

int main(void) {
    std::string word = "code";

    std::cout << "First: " << word[0] << std::endl;
    std::cout << "Last: " << word[3] << std::endl;

    word[0] = 'm';
    std::cout << "Changed: " << word << std::endl;

    return 0;
}

Output:

First: c
Last: e
Changed: mode

Use single quotes for one character, such as 'm', and double quotes for text strings, such as "mode".

Common Mistakes

  • Forgetting #include <string> before using std::string.
  • Using single quotes for strings. Single quotes are for one char; strings use double quotes.
  • Expecting indexes to start at 1. The first character is at index 0.
  • Accessing an index that is outside the string, such as word[10] when the string is shorter.

Takeaway: use std::string for text, + to join strings, length() to count characters, and indexes to read or change individual characters.