CodeMIRAI
0 XP

std::string

3 min read 6 runnable examples Quiz included

C stores text in char arrays and makes you manage their size. C++'s std::string handles that for you: it grows as needed, knows its own length, and comes with methods for searching and editing.

Making and joining strings

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

int main() {
    string first = "Ada";
    string last = "Lovelace";
    string full = first + " " + last;
    cout << full << endl;
    cout << full.length() << " characters" << endl;
    cout << full[0] << full[4] << endl;
    full += ", mathematician";
    cout << full << endl;
    return 0;
}
Output
Ada Lovelace
12 characters
AL
Ada Lovelace, mathematician
  • + joins strings and += appends to one.
  • length() (or size(), the same thing) counts characters.
  • full[0] is the first character, a char. full.at(0) does the same but checks the position and throws an error if it's out of range.

Searching and slicing

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

int main() {
    string email = "asha.k@example.com";
    size_t at = email.find('@');
    string user = email.substr(0, at);         // from position 0, at characters long
    string domain = email.substr(at + 1);      // from at + 1 to the end
    cout << user << " | " << domain << endl;

    if (email.find("gmail") == string::npos)
        cout << "not a gmail address" << endl;
    return 0;
}
Output
asha.k | example.com
not a gmail address
  • find returns the position of the first match, or the special value string::npos when there isn't one. Always compare against npos before using the position.
  • substr(start, count) copies part of the string; leave out count to go to the end.

Changing parts of a string

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

int main() {
    string s = "I like cats. cats are great.";
    size_t pos = 0;
    while ((pos = s.find("cats", pos)) != string::npos) {
        s.replace(pos, 4, "dogs");     // replace 4 characters at pos
        pos += 4;                      // keep searching after the replacement
    }
    cout << s << endl;

    string code = "ABC-123-XYZ";
    code.erase(3, 1);                  // remove 1 character at position 3
    code.insert(0, "ID:");
    cout << code << endl;
    return 0;
}
Output
I like dogs. dogs are great.
ID:ABC123-XYZ

replace, erase and insert edit the string in place. Moving pos past each replacement matters: without it, a replacement that contains the search word would be found again forever.

Reading a whole line

This example's input is Ada Lovelace, then 36:

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

int main() {
    string name;
    int age;
    cout << "Full name? ";
    getline(cin, name);          // the whole line, spaces included
    cout << "Age? ";
    cin >> age;
    cout << endl << "Hello, " << name << ". Next year you'll be " << age + 1 << "." << endl;
    return 0;
}
Output
Full name? Age? 
Hello, Ada Lovelace. Next year you'll be 37.

cin >> name stops at the first space, so it would read only Ada. getline(cin, s) reads up to the end of the line.

One trap: after cin >> number, the newline you typed is still waiting, so a following getline reads an empty line. Call cin.ignore() between them to skip it:

C++
cin >> age;
cin.ignore();            // drop the leftover newline
getline(cin, city);

Characters, and converting numbers

C++
#include <cctype>
#include <iostream>
#include <string>
using namespace std;

int main() {
    string text = "Hello World 2026";
    int letters = 0, digits = 0;
    string upper;
    for (char c : text) {
        if (isalpha(static_cast<unsigned char>(c))) letters++;
        if (isdigit(static_cast<unsigned char>(c))) digits++;
        upper += static_cast<char>(toupper(static_cast<unsigned char>(c)));
    }
    cout << upper << endl;
    cout << letters << " letters, " << digits << " digits" << endl;

    int n = stoi("42");
    double price = stod("19.99");
    cout << n * 2 << " " << price + 0.01 << endl;
    cout << "Level " + to_string(7) << endl;
    return 0;
}
Output
HELLO WORLD 2026
10 letters, 4 digits
84 20
Level 7
  • A range-for loop visits each char. The <cctype> functions classify and convert characters; casting to unsigned char keeps them safe for every character value.
  • stoi and stod turn text into an int or a double (and throw an error if the text isn't a number).
  • to_string goes the other way.

Comparing strings

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

int main() {
    string a = "apple", b = "banana", c = "Apple";
    cout << (a == "apple") << endl;
    cout << (a < b) << endl;           // dictionary order
    cout << (c < a) << endl;           // capital letters sort before lowercase
    return 0;
}
Output
1
1
1

==, !=, < and > compare strings character by character, which is why sorting a list of strings puts them in dictionary order. Uppercase letters have smaller character codes than lowercase ones, so "Apple" comes before "apple".

Finished this lesson?Mark it complete to earn +20 XP and move your progress on.