LearnFrenzy
Sign in Take a free test

Variables, References and Strings · Lesson 6 of 33

std::string in C++

5 min read Updated Nov 7, 2026 Saurabh Samir

In C, a string is a char array you must size, terminate and copy by hand. C++'s std::string manages its own memory, grows as needed, and supports +, == and dozens of methods. It's what you should use for text in every C++ program – and string tasks fill a big share of coding interviews.

In this lesson

  • Creating, joining and comparing strings
  • find, substr, replace, insert and erase
  • Converting between numbers and strings
  • std::string_view and classic string tasks

The basics

#include <iostream>
#include <string>

int main() {
    std::string first = "Asha", last = "Verma";
    std::string full = first + " " + last;              // + joins strings
    full += " (CSE)";                                   // append

    std::cout << full << '\n';
    std::cout << "length: " << full.size() << ", first char: " << full[0]
              << ", last char: " << full.back() << '\n';
    std::cout << std::boolalpha << (first == "Asha") << ' ' << (first < last) << '\n';   // real comparison
    std::cout << "empty? " << std::string{}.empty() << '\n';
    return 0;
}

Output

Asha Verma (CSE)
length: 16, first char: A, last char: )
true true
empty? true

Unlike C strings, == and < compare contents (alphabetically, by character code). size() (or length()) is stored, so it's instant.

Searching and slicing

#include <iostream>
#include <string>

int main() {
    std::string email = "asha.verma@learnfrenzy.com";
    std::size_t at = email.find('@');
    if (at != std::string::npos) {                      // npos = "not found"
        std::string user = email.substr(0, at);         // from 0, at characters
        std::string domain = email.substr(at + 1);      // from at+1 to the end
        std::cout << user << " | " << domain << '\n';
    }
    std::cout << email.find("frenzy") << ' ' << (email.find("xyz") == std::string::npos) << '\n';
    std::cout << email.rfind('.') << '\n';               // last '.'
    std::cout << std::boolalpha << email.starts_with("asha") << ' ' << email.ends_with(".com") << '\n';   // C++20
    return 0;
}

Output

asha.verma | learnfrenzy.com
16 1
22
true true

Modifying strings

#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>

int main() {
    std::string s = "C is fun";
    s.replace(0, 1, "C++");                 // replace 1 char at 0 with "C++"
    s.insert(s.size(), "!");                // insert at the end
    std::cout << s << '\n';

    s.erase(4, 3);                          // remove 3 chars from index 4 ("is ")
    std::cout << s << '\n';

    std::reverse(s.begin(), s.end());       // STL algorithms work on strings
    std::cout << s << '\n';

    std::string shout = "learn frenzy";
    std::transform(shout.begin(), shout.end(), shout.begin(),
                   [](unsigned char c) { return static_cast<char>(std::toupper(c)); });
    std::cout << shout << '\n';
    return 0;
}

Output

C++ is fun!
C++ fun!
!nuf ++C
LEARN FRENZY

Numbers ↔ strings

#include <iostream>
#include <sstream>
#include <string>

int main() {
    std::string order = "ORD-" + std::to_string(1042);       // number → string
    int qty = std::stoi("25");                               // string → int
    double price = std::stod("249.50");                      // string → double
    std::cout << order << ' ' << qty * price << '\n';

    try {
        std::cout << std::stoi("abc");                       // throws, so nothing is printed
    } catch (const std::invalid_argument&) {
        std::cout << "\"abc\" is not a number\n";
    }

    std::istringstream line("Asha 21 88.5");                 // split a line into typed values
    std::string name; int age; double marks;
    line >> name >> age >> marks;
    std::cout << name << " is " << age << " and scored " << marks << '\n';
    return 0;
}

Output

ORD-1042 6237.5
"abc" is not a number
Asha is 21 and scored 88.5

string_view: read-only, no copy

#include <iostream>
#include <string>
#include <string_view>

int count_vowels(std::string_view s) {          // accepts string, literal or part of a string – no copy
    int n = 0;
    for (char c : s) if (std::string_view{"aeiouAEIOU"}.find(c) != std::string_view::npos) n++;
    return n;
}

int main() {
    std::string course = "Competitive Programming";
    std::cout << count_vowels(course) << ' ' << count_vowels("Algorithms") << ' '
              << count_vowels(std::string_view{course}.substr(0, 11)) << '\n';
    return 0;
}

Output

8 3 5

string_view doesn't own its characters

It's a window onto someone else's string. Never return a string_view into a local std::string, and never keep one after the original string changes or is destroyed – it would dangle.

Practice

Try it yourself

  1. Check whether "Racecar" is a palindrome ignoring case, using std::string and std::equal.

    Show solution
    #include <algorithm>
    #include <cctype>
    #include <iostream>
    #include <string>
    
    int main() {
        std::string s = "Racecar";
        for (char& c : s) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
        bool pal = std::equal(s.begin(), s.begin() + s.size() / 2, s.rbegin());
        std::cout << std::boolalpha << pal << '\n';
        return 0;
    }

    Output

    true

Quick check

What does find return when the text isn't found?

std::string::npos.

What do substr(2, 3)'s arguments mean?

Start at index 2, take 3 characters.

When should a function take a string_view?

When it only reads the text and doesn't keep it – it accepts any string without copying.

Summary

  • std::string manages memory; + joins, == and < compare contents.
  • find/substr/replace/insert/erase edit text; STL algorithms work on strings.
  • to_string/stoi/stod convert; string_view passes read-only text without copying.

Finished this lesson?

Mark it complete to track your progress, then carry on with the next lesson.

Next lesson

Search LearnFrenzy

Esc

Quick links