Curriculum / C++ / Lesson 10

Strings in C++

Unlike C, C++ has a proper string type: std::string (from the <string> header).

10 of 10
beginner 📖 5 min read 🎯 1 question

Strings

Unlike C, C++ has a proper string type: std::string (from the <string> header). It manages its own memory, can grow automatically, and supports simple operators like + for concatenation.

💡 Key insight std::string removes almost all the manual memory-management headaches that come with C-style char arrays.

Syntax

syntax
#include <string>
string name = "text";
name.length();
name + otherString;

Example

.length() (or .size()) returns the number of characters in the string.

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

int main() {
    string name = "CodeyHub";
    cout << "Name: " << name << endl;
    cout << "Length: " << name.length() << endl;
    return 0;
}
outputName: CodeyHub Length: 8

Try it yourself

Copy this example into the C++ compiler and run it — try changing a value and see what happens.

Quick Quiz

1. Which operator can you use to join two std::string values in C++?

Back to curriculum