CodeBlanks Logo Icon CodeBlanks

std::string

Learn to store text with std::string.

std::string

std::string is the type for holding text. With std::string name = "Alice"; you can store text of any length. To use std::string you include the #include <string> header (most of the time <iostream> pulls it in indirectly, but writing it explicitly is safer).

std::string is safer and more convenient than C-style character arrays (char[]): it manages the length automatically and does not leak memory.

You can concatenate two strings with +: std::string full = first + " " + last;. This makes text operations easy.

string operations

Common operations with std::string:

  • Length: name.length() or name.size() gives the character count
  • Concatenation: + joins two strings side by side
  • Access: name[0] gives the first character
  • Comparison: == checks whether two strings are the same

Example: std::string greeting = "Hello " + name; builds a greeting string. greeting.length() gives the number of characters.

Practice Concatenate strings and print

Add the #include <string> header. Inside main, declare two std::string variables: firstName with value "Alice" and lastName with value "Smith". Declare a third std::string named fullName as firstName + " " + lastName. Print fullName with std::cout using std::endl.

Starter code

main.cpp
#include <iostream>

int main() {
    // Declare firstName and lastName
    // Define fullName by concatenation
    // Print fullName with std::cout
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <string>

int main() {
    // Declare firstName and lastName
    std::string firstName = "Alice";
    std::string lastName = "Smith";
    // Define fullName by concatenation
    std::string fullName = firstName + " " + lastName;
    // Print fullName with std::cout
    std::cout << fullName << std::endl;
    return 0;
}

Expected output

Alice Smith

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which header is included to use std::string?

  • <vector>
  • <string> Correct answer
  • <map>
  • <list>

Explanation: std::string is defined in the <string> header.

2 Match string operations

Term Meaning
+ Concatenation
length() Character count
[0] First character
== Equality comparison

3 String declaration

Question
____ name = "Alice";
Answer
std::string name = "Alice";

Explanation: Text is stored in std::string.

All lessons in Beginner