TExcelTAD
Home › C++ › C++ Strings

C++ Strings

A string is a sequence of characters. Modern C++ uses the std::string class from the <string> header. Unlike the raw character arrays of C, a std::string knows its own length, grows automatically and cleans up its memory for you.

Creating and joining strings

Use + to concatenate (join) strings, or += to append to an existing one:

cpp · try it yourself
#include <iostream>
#include <string>
using namespace std;

int main() {
    string first = "Grace";
    string last = "Hopper";
    string full = first + " " + last;
    cout << full << "\n";

    string greeting = "Hi";
    greeting += ", ";
    greeting += full;
    greeting += '!';
    cout << greeting << "\n";
}
Grace Hopper
Hi, Grace Hopper!

Note: You cannot add two string literals directly: "a" + "b" does not compile, because literals are plain character arrays. At least one side of + must be a std::string.

Length and individual characters

size() (or its synonym length()) returns the number of characters. Characters are numbered from 0; access them with [] or the bounds-checked at():

cpp · try it yourself
#include <iostream>
#include <string>
using namespace std;

int main() {
    string word = "planet";
    cout << "Length: " << word.size() << "\n";
    cout << "First: " << word[0] << "\n";
    cout << "Last: " << word[word.size() - 1] << "\n";
    cout << "Also last: " << word.back() << "\n";

    word[0] = 'P';
    cout << word << "\n";
}
Length: 6
First: p
Last: t
Also last: t
Planet

word[10] on a 6-character string is undefined behaviour, while word.at(10) throws an exception you can catch — useful while learning.

Useful member functions

Function What it does
s.substr(pos, len) Copy of len characters starting at pos
s.find(text) Index of the first match, or string::npos
s.replace(pos, len, text) Replace a range with other text
s.insert(pos, text) Insert text before pos
s.erase(pos, len) Remove characters
s.empty() true if the string has no characters
s.starts_with(x) / s.ends_with(x) Prefix / suffix test (C++20)
cpp · try it yourself
#include <iostream>
#include <string>
using namespace std;

int main() {
    string email = "lin.chen@example.org";
    size_t at = email.find('@');
    string user = email.substr(0, at);
    string domain = email.substr(at + 1);
    cout << "User: " << user << "\n";
    cout << "Domain: " << domain << "\n";
    cout << boolalpha << domain.ends_with(".org") << "\n";

    if (email.find("gmail") == string::npos) {
        cout << "Not a gmail address\n";
    }
}
User: lin.chen
Domain: example.org
true
Not a gmail address

Numbers and strings

Convert a number to text with to_string, and text to a number with stoi (int) or stod (double):

cpp · try it yourself
#include <iostream>
#include <string>
using namespace std;

int main() {
    int year = 2024;
    string label = "Year " + to_string(year);
    cout << label << "\n";

    string qty = "42";
    string price = "3.5";
    cout << stoi(qty) * stod(price) << "\n";
}
Year 2024
147

Looping over characters

A range-based for visits every character. Here we count vowels and build an upper-case copy using toupper from <cctype>:

cpp · try it yourself
#include <iostream>
#include <string>
#include <cctype>
using namespace std;

int main() {
    string text = "Hello World";
    int vowels = 0;
    string upper;
    for (char c : text) {
        char lower = tolower(c);
        if (lower == 'a' || lower == 'e' || lower == 'i' || lower == 'o' || lower == 'u') {
            vowels++;
        }
        upper += toupper(c);
    }
    cout << vowels << " vowels\n" << upper << "\n";
}
3 vowels
HELLO WORLD

Test yourself

What does string("banana").find("na") return?

  1. 1
  2. 2
  3. 4
  4. string::npos

Which line does NOT compile?

  1. string s = "a" + string("b");
  2. string s = "a" + "b";
  3. string s = "a"; s += "b";
  4. string s = string("a") + 'b';

Which function converts the string "15" to the int 15?

  1. to_string
  2. stoi
  3. atoi_s
  4. int.parse