C++ Strings

A string is a piece of text, such as a name, a message, or a whole sentence. C++ stores text in a handy type called string, which lets you hold and work with words as easily as you work with numbers.

Creating strings

To use strings in C++ you include the <string> library. Then you can declare a variable of type string and put text inside double quotes. That text is called a string literal.

Your first string

#include <iostream>
#include <string>
using namespace std;

int main() {
  string greeting = "Hello, world!";
  cout << greeting << "\n";
  return 0;
}

You can create an empty string and fill it later, or change a string's contents at any time by assigning new text to it. Strings are flexible and can grow or shrink as needed, unlike a fixed block of characters.

Changing a string

#include <iostream>
#include <string>
using namespace std;

int main() {
  string name = "Ada";
  cout << "Before: " << name << "\n";

  name = "Grace"; // replace the whole value
  cout << "After: " << name << "\n";
  return 0;
}
  • Include <string> to use the string type
  • Text goes inside double quotes: "like this"
  • Single quotes like 'A' are for one character, not a string
  • A string can be empty, one letter, or a whole paragraph

String basics

CodeMeaning
string s;An empty string
string s = "Hi";A string holding the text Hi
s = "Bye";Replace the contents with Bye
cout << s;Print the string to the screen
Note: The string type comes from the C++ Standard Library. Writing using namespace std; lets you type string instead of the longer std::string. Both mean the same thing.

Exercise: C++ Strings

What must you do to use std::string in a C++ program?