Chapter 18 of 48

Strings

Names, passwords, messages, file contents, DNA sequences: a huge share of real programs is about text. In C++ a piece of text is called a string.

C++ actually has two kinds of strings. The old one, inherited from C, is a plain array of characters ending with a special '\0' character. The modern one is the library class std::string, which manages its own memory, grows as needed and comes with dozens of useful operations. In this chapter we will focus on std::string, because it is what you should use in almost all new code, and then look at C-style strings and std::string_view so you can read older code and answer exam questions. We will build on the Arrays topic, since a C-style string is just a char array.

What is std::string?

std::string is a standard library class (header <string>) that stores a sequence of characters in contiguous memory, keeps track of its own length, and automatically grows or shrinks as the text changes.

Unlike a char array, you never decide its size in advance, you can copy it with =, compare it with ==, and join two strings with +. Unlike Java's String, a C++ std::string is mutable: you can change its characters in place.


Creating and Joining Strings

#include <iostream>
#include <string>

int main() {
    std::string first = "Asha";          // from a string literal
    std::string last("Verma");           // constructor syntax
    std::string stars(5, '*');           // 5 copies of '*'
    std::string empty;                   // empty string ""

    std::string full = first + " " + last;   // concatenation
    full += '!';                             // append a char
    full.append(" Welcome.");                // append a string

    std::cout << full << '\n';
    std::cout << stars << '\n';
    std::cout << "Length: " << full.length()
              << " (size() gives the same: " << full.size() << ")\n";
    std::cout << std::boolalpha << "empty is empty? " << empty.empty() << '\n';

    std::cout << "First char: " << full[0]
              << ", last char: " << full.back() << '\n';
    full[0] = 'U';                           // strings are mutable
    std::cout << full << '\n';
}

Output:

Asha Verma! Welcome.
*****
Length: 20 (size() gives the same: 20)
empty is empty? true
First char: A, last char: .
Usha Verma! Welcome.
  • length() and size() are exactly the same thing; size() matches the other standard containers. Both are O(1) because the string stores its length.

  • empty() is the clean way to test for "".

  • s[i] gives the character at index i (indexes start at 0, as with arrays). front() and back() give the first and last character; calling them on an empty string is undefined behaviour.

  • + creates a new string; += and append add to the existing one, which is usually more efficient inside loops.


[] vs at(): Bounds Checking

Just like arrays, s[i] does no bounds checking: an index greater than s.size() is undefined behaviour. (Reading s[s.size()] is allowed and gives '\0'.) The member function at(i) checks the index and throws a std::out_of_range exception if it is invalid:

#include <iostream>
#include <string>

int main() {
    std::string s = "hello";
    std::cout << s[1] << ' ' << s.at(1) << '\n';   // both fine
    std::cout << s.at(10) << '\n';                  // throws std::out_of_range
}

Output in a terminal with GCC (the first line goes to standard output; the other two are printed to the error stream, and their exact text depends on the library):

e e
terminate called after throwing an instance of 'std::out_of_range'
  what():  basic_string::at: __n (which is 10) >= this->size() (which is 5)

Since we do not catch the exception, the program is terminated. We will learn to catch exceptions in the Exception Handling topic. Use [] in loops where you control the index; use at() when the index comes from outside (user input, a file) and you want a clean failure instead of silent memory corruption.


Comparing Strings

std::string supports ==, !=, <, >, <= and >=. They compare the contents, character by character, using the characters' numeric codes. This is called lexicographic (dictionary) order.

#include <iostream>
#include <string>

int main() {
    std::string a = "apple", b = "banana", c = "Apple", d = "app";

    std::cout << std::boolalpha;
    std::cout << (a == "apple") << '\n';   // true: compares contents
    std::cout << (a < b) << '\n';          // true: 'a' < 'b'
    std::cout << (c < a) << '\n';          // true: 'A' (65) < 'a' (97)
    std::cout << (d < a) << '\n';          // true: a prefix is smaller
    std::cout << a.compare(b) << ' '       // negative, zero or positive
              << a.compare("apple") << ' '
              << b.compare(a) << '\n';
}

Output:

true
true
true
true
-1 0 1

How lexicographic comparison works:

  1. Compare the strings from the left until two characters differ. The string with the smaller character is smaller ("apple" < "banana" because 'a' < 'b').

  2. If one string runs out first, the shorter one (the prefix) is smaller ("app" < "apple").

  3. Uppercase letters (65 to 90 in ASCII) come before lowercase ones (97 to 122), so "Zebra" < "apple" is true. For case-insensitive comparison, convert both strings to the same case first.

a.compare(b) returns a negative number, zero, or a positive number. The standard only promises the sign: GCC happened to print -1 and 1 above, but another library (or a different pair of strings) may give other values such as -98 or 2, so never test for exactly -1.


Reading Strings from Input

We met std::cin and std::getline in the Input & Output topic. With strings, two facts cause most beginner bugs:

  • std::cin >> s skips leading whitespace and then reads one word, stopping at the next space, tab or newline.

  • std::getline(std::cin, s) reads a whole line, up to the newline. The newline is removed from the input and not stored in s.

Mixing the two causes a famous problem. Input:

21
Rahul Kumar
#include <iostream>
#include <string>

int main() {
    int age;
    std::string name;

    std::cin >> age;               // reads 21, leaves '\n' in the input
    std::getline(std::cin, name);  // reads up to that '\n' -> empty line!

    std::cout << "age = " << age << ", name = [" << name << "]\n";
}

Output:

age = 21, name = []

The name is empty! std::cin >> age read 21 but left the newline after it in the input. getline then saw that newline immediately and returned an empty line. The fix is to throw away the leftover whitespace first, with std::ws (or std::cin.ignore(...)):

21
Rahul Kumar
Priya Sharma
#include <iostream>
#include <string>

int main() {
    int age;
    std::string first, name;

    std::cin >> age;
    std::getline(std::cin >> std::ws, name);   // std::ws skips the leftover '\n'
    std::cin >> first;                         // operator>> reads ONE word

    std::cout << "age = " << age << ", name = [" << name << "]\n";
    std::cout << "first = [" << first << "]\n";
}

Output:

age = 21, name = [Rahul Kumar]
first = [Priya]

Notice that std::cin >> first stopped at the space and took only "Priya". Use getline whenever the input may contain spaces.


Searching, Extracting and Modifying

#include <iostream>
#include <string>

int main() {
    std::string s = "I love C++ and I love coding";

    // searching
    std::cout << "find(\"love\")    = " << s.find("love") << '\n';
    std::cout << "rfind(\"love\")   = " << s.rfind("love") << '\n';
    std::cout << "find(\"love\", 3) = " << s.find("love", 3) << '\n';

    std::size_t pos = s.find("Java");
    if (pos == std::string::npos) {
        std::cout << "\"Java\" not found\n";
    }

    // extracting
    std::cout << "substr(2, 4) = " << s.substr(2, 4) << '\n';
    std::cout << "substr(15)   = " << s.substr(15) << '\n';

    // modifying
    std::string t = s;
    t.replace(t.find("C++"), 3, "Python");     // replace 3 chars at that position
    std::cout << t << '\n';
    t.insert(0, ">> ");
    std::cout << t << '\n';
    t.erase(0, 3);                             // remove 3 chars from index 0
    std::cout << t << '\n';

    // C++20 and C++23 helpers
    std::cout << std::boolalpha
              << s.starts_with("I love") << ' '    // C++20
              << s.ends_with("coding") << ' '      // C++20
              << s.contains("C++") << '\n';        // C++23
}

Output:

find("love")    = 2
rfind("love")   = 17
find("love", 3) = 17
"Java" not found
substr(2, 4) = love
substr(15)   = I love coding
I love Python and I love coding
>> I love Python and I love coding
I love Python and I love coding
true true true

Function

What it does

Note

find(x) / find(x, from)

Index of the first occurrence of x (a string or char), searching from index from

Returns std::string::npos if not found

rfind(x)

Index of the last occurrence

Also returns npos if not found

find_first_of(chars)

First position of any of the given characters

Handy for finding separators

substr(pos, len)

New string of at most len characters starting at pos

Without len: till the end. Throws out_of_range if pos > size()

replace(pos, len, str)

Replaces len characters at pos with str

Lengths may differ

insert(pos, str)

Inserts str before index pos

Shifts the rest: O(n)

erase(pos, len)

Removes len characters from pos

Shifts the rest: O(n)

push_back(c) / pop_back()

Add / remove one character at the end

pop_back on an empty string is UB

clear()

Makes the string empty

starts_with, ends_with

Prefix / suffix test

C++20

contains

Substring or character test

C++23

Always check for npos

std::string::npos is the largest value of std::size_t (a huge unsigned number), used to mean "not found". A classic bug is using the result of find without checking it:

std::size_t pos = s.find("Java");      // npos: not found
std::string rest = s.substr(pos);      // throws std::out_of_range

Also, store the result in std::size_t (or auto), not in int: converting npos to int gives -1 on common systems, which hides the mistake and invites signed/unsigned bugs. The standard does not say which search algorithm find uses; common implementations do a simple scan whose worst case is about O(n × m) for a text of length n and a pattern of length m. For huge texts, algorithms like KMP (or std::boyer_moore_searcher, C++17) are better.


Converting Between Numbers and Strings

#include <iostream>
#include <string>

int main() {
    int roll = 42;
    double cgpa = 8.75;

    std::string label = "Roll " + std::to_string(roll);   // number -> string
    std::cout << label << '\n';
    std::cout << std::to_string(cgpa) << '\n';

    int n = std::stoi("2025");               // string -> int
    double d = std::stod("3.14");            // string -> double
    int partial = std::stoi("  77 marks");   // skips leading spaces, stops at ' '
    std::cout << n + 1 << ' ' << d * 2 << ' ' << partial << '\n';

    std::cout << std::stoi("ff", nullptr, 16) << ' '      // base 16
              << std::stoi("1011", nullptr, 2) << '\n';   // base 2
}

Output:

Roll 42
8.750000
2026 6.28 77
255 11
  • std::to_string (C++11) turns a number into a string. For a double it uses six decimal places, like printf("%f"), which is why 8.75 became "8.750000". (C++26 changes this to the shortest form that reads back exactly; GCC 15 with -std=c++26 already prints "8.75".)

  • std::stoi, std::stol, std::stoll and std::stod (C++11) go the other way. They skip leading whitespace and convert as many characters as they can, so " 77 marks" gives 77.

  • If no conversion is possible (for example std::stoi("abc")), they throw std::invalid_argument; if the number does not fit, they throw std::out_of_range.

  • The optional third argument is the base: std::stoi("ff", nullptr, 16) is 255.


Working with Individual Characters

A std::string is a sequence of char, so the range-based for loop from the Arrays topic works directly. The character functions in <cctype> (isdigit, isalpha, isspace, toupper, tolower, ...) are handy here, with one subtlety explained below.

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

bool isPalindrome(const std::string& s) {
    if (s.empty()) return true;
    std::size_t i = 0, j = s.size() - 1;
    while (i < j) {
        if (s[i] != s[j]) return false;
        ++i;
        --j;
    }
    return true;
}

int main() {
    std::string text = "Hello World 2026";

    int vowels = 0, digits = 0, spaces = 0;
    for (char ch : text) {
        unsigned char u = static_cast<unsigned char>(ch);
        char lower = static_cast<char>(std::tolower(u));
        if (lower == 'a' || lower == 'e' || lower == 'i' ||
            lower == 'o' || lower == 'u') ++vowels;
        else if (std::isdigit(u)) ++digits;
        else if (std::isspace(u)) ++spaces;
    }
    std::cout << "vowels=" << vowels << " digits=" << digits
              << " spaces=" << spaces << '\n';

    std::string upper = text;
    for (char& ch : upper) {
        ch = static_cast<char>(std::toupper(static_cast<unsigned char>(ch)));
    }
    std::cout << upper << '\n';

    std::string reversed(text.rbegin(), text.rend());
    std::cout << reversed << '\n';

    std::cout << std::boolalpha << isPalindrome("madam") << ' '
              << isPalindrome("hello") << ' ' << isPalindrome("") << '\n';
}

Output:

vowels=3 digits=4 spaces=2
HELLO WORLD 2026
6202 dlroW olleH
true false true
  • Why the static_cast<unsigned char>? The <cctype> functions take an int that must be either EOF or a value representable as unsigned char. On most systems char is signed, so a non-ASCII character (like é in some encodings) is a negative number, and passing it directly is undefined behaviour. Casting to unsigned char first makes it safe.

  • for (char& ch : upper) uses a reference so we can change the characters in place (more in the References topic).

  • std::string reversed(text.rbegin(), text.rend()); builds a new string by walking the original backwards using reverse iterators (see the Iterators topic).

  • isPalindrome takes const std::string& so the string is not copied. The two-index loop is the same idea as reversing an array: compare the ends, move inwards. The empty-string check matters because s.size() - 1 on an empty string would wrap around to a huge unsigned number.


C-Style Strings

Before std::string, text in C and C++ was stored as a null-terminated character array: the characters followed by a '\0' (the character with value 0) marking the end.

char name[] = "Ravi";

index:   [0]   [1]   [2]   [3]   [4]
        ┌─────┬─────┬─────┬─────┬─────┐
        │ 'R' │ 'a' │ 'v' │ 'i' │'\0' │
        └─────┴─────┴─────┴─────┴─────┘
sizeof(name) = 5      strlen(name) = 4

The functions for C-strings live in <cstring>:

#include <cstring>
#include <iostream>
#include <string>

int main() {
    char name[] = "Ravi";              // 5 chars: R a v i \0
    std::cout << "sizeof = " << sizeof(name)
              << ", strlen = " << std::strlen(name) << '\n';

    char buf[20];
    std::strcpy(buf, name);            // copy (buf must be big enough!)
    std::strcat(buf, " Kumar");        // append
    std::cout << buf << " (" << std::strlen(buf) << " chars)\n";

    std::cout << (std::strcmp("abc", "abd") < 0) << '\n';   // 1: "abc" comes first

    // converting between the two worlds
    std::string s = buf;               // C-string -> std::string
    std::cout << s.size() << ' ' << s.c_str() << '\n';   // c_str(): std::string -> C-string
}

Output:

sizeof = 5, strlen = 4
Ravi Kumar (10 chars)
1
10 Ravi Kumar

Function

Purpose

Cost and danger

strlen(s)

Number of characters before '\0'

O(n): it must scan for the terminator

strcpy(dst, src)

Copy src into dst

No size check: overflow if dst is too small

strcat(dst, src)

Append src to dst

No size check

strcmp(a, b)

Compare contents

Returns negative / 0 / positive

Things that make C-strings risky:

  • The array must have room for the '\0'. char s[4] = "Ravi"; is an error in C++ (it is allowed in C, which silently drops the terminator).

  • strcpy and strcat never check the destination size. Writing past the end is a buffer overflow, one of the most common security bugs in history.

  • == on two char arrays compares addresses, not text, exactly like the array comparison problem in the Arrays topic. Use strcmp.

  • A string literal such as "Ravi" has type const char[5] and must never be modified.

You still need C-strings to call C libraries and operating-system functions. s.c_str() gives a read-only, null-terminated version of a std::string for that purpose, and assigning a C-string to a std::string copies it. Remember that the result of c_str() becomes invalid as soon as the std::string is modified or destroyed.


Why "Hello" + " World" Does Not Compile

A string literal is not a std::string; it is a const char array. Two arrays cannot be added:

#include <string>

int main() {
    std::string s = "Hello" + " World";
}
s10_nocompile_plus.cpp: In function ‘int main()’:
s10_nocompile_plus.cpp:4:29: error: invalid operands of types ‘const char [6]’ and ‘const char [7]’ to binary ‘operator+’
    4 |     std::string s = "Hello" + " World";
      |                     ~~~~~~~ ^ ~~~~~~~~
      |                     |         |
      |                     |         const char [7]
      |                     const char [6]

It works as soon as at least one side of each + is a std::string. Since C++14 the s suffix creates a std::string literal directly:

#include <iostream>
#include <string>

int main() {
    using namespace std::string_literals;   // enables the s suffix (C++14)

    auto a = "Hello";        // a is const char* (a C-string)
    auto b = "Hello"s;       // b is std::string

    std::string ok1 = std::string("Hello") + " World";
    std::string ok2 = b + " World";
    std::cout << ok1 << " | " << ok2 << " | " << a << '\n';
}

Output:

Hello World | Hello World | Hello

Note that auto a = "Hello"; gives a const char*, not a std::string. This surprises many people, and is another reason the s suffix is useful. Because + groups from left to right (x + y + z means (x + y) + z), s + "a" + "b" works but "a" + "b" + s does not.


std::string_view (C++17)

Passing const std::string& to a function avoids a copy, but if the caller passes a string literal, a temporary std::string must still be created. std::string_view (header <string_view>) is a lightweight, read-only window onto characters that live somewhere else: it stores only a pointer and a length.

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

// Accepts std::string, string literals and char arrays without copying.
std::size_t countChar(std::string_view text, char c) {
    std::size_t count = 0;
    for (char ch : text) {
        if (ch == c) ++count;
    }
    return count;
}

int main() {
    std::string s = "banana";
    std::cout << countChar(s, 'a') << ' '
              << countChar("mississippi", 's') << '\n';

    std::string_view sv = "Hello, World";
    std::cout << sv.substr(7, 5) << '\n';   // a view, no new string made
    sv.remove_prefix(7);
    std::cout << sv << " (" << sv.size() << ")\n";
}

Output:

3 4
World
World (5)

substr on a string_view is O(1): it just makes a smaller window, no characters are copied. The big rule: a string_view does not own its characters. If the string it looks at is destroyed or changed, the view dangles, and using it is undefined behaviour:

std::string_view bad = std::string("temp");   // the temporary string dies at the ;
std::cout << bad;                             // undefined behaviour: dangling view

Use std::string_view for function parameters that only read text. Use std::string when you need to store or modify the text.


How std::string Manages Memory

A std::string keeps three things: a pointer to its characters, its size (characters in use) and its capacity (characters it can hold before it must allocate a larger buffer). When it runs out of room, it allocates a bigger buffer, copies the characters over and frees the old one. Watching the capacity with GCC's library:

#include <iostream>
#include <string>

int main() {
    std::string s;
    std::cout << "size " << s.size() << ", capacity " << s.capacity() << '\n';
    for (int i = 0; i < 40; ++i) {
        std::size_t before = s.capacity();
        s += 'x';
        if (s.capacity() != before) {
            std::cout << "size " << s.size() << ", capacity " << s.capacity() << '\n';
        }
    }
}

Output (libstdc++; other libraries grow differently):

size 0, capacity 15
size 16, capacity 30
size 31, capacity 60

Two implementation details show up here. First, an empty string already holds 15 characters: short strings are stored inside the string object itself, with no heap allocation at all. This is called the small string optimisation (SSO); the limit is 15 characters in libstdc++ (GCC) and 22 in libc++ (Clang) on 64-bit systems. Second, the capacity roughly doubles each time, so appending one character at a time costs amortised O(1) per character. If you know the final size in advance, call s.reserve(n) to allocate once.


std::string vs C-Style String

Feature

std::string

C-style char[]

Size

Grows automatically

Fixed when declared

Length

size(), O(1)

strlen(), O(n)

Copy

a = b

strcpy (unchecked)

Join

a + b, a += b

strcat (unchecked)

Compare

==, < on contents

strcmp (== compares addresses)

Can contain '\0' inside

Yes

No, it marks the end

Memory management

Automatic

Manual

Use for

Almost all C++ code

C APIs, very low-level code


Common Mistakes

  • Forgetting #include <string>. It may compile by accident because <iostream> sometimes includes it, but that is not guaranteed.

  • Using getline right after cin >> and getting an empty line. Use std::cin >> std::ws first.

  • Not checking find against npos, or storing its result in an int.

  • Writing "a" + "b", which tries to add two arrays.

  • Passing a plain char to toupper/isdigit without casting to unsigned char.

  • Passing std::string by value to functions that only read it. Use const std::string& or std::string_view.

  • Keeping a string_view or c_str() pointer after the original string has changed or died.

  • Building a long string with repeated s = s + x, which creates a new string every time. Use s += x.


Interview Questions

What is the difference between size() and length() of std::string?

None. They return the same value. length() exists for readability; size() exists for consistency with other containers.

What does sizeof return for char s[] = "GATE"; and what does strlen return?

sizeof(s) is 5 (four letters plus '\0'). strlen(s) is 4 (it does not count the terminator).

What does s.find("x") return when "x" is not present?

std::string::npos, which is the maximum value of std::size_t, i.e. static_cast<std::size_t>(-1).

What is the difference between s[i] and s.at(i)?

s[i] does no bounds check (an index above size() is undefined behaviour). s.at(i) checks the index and throws std::out_of_range if i >= size().

Is std::string mutable? How is that different from Java?

Yes, a std::string can be changed in place (s[0] = 'X', s += "..."). Java's String is immutable; changing it creates a new object, which is why Java has StringBuilder.

What is the small string optimisation?

An implementation technique where short strings are stored in a buffer inside the std::string object itself, avoiding a heap allocation. It is not required by the standard, but all major libraries do it (15 characters in libstdc++, 22 in libc++, on 64-bit).

Why is auto s = "hi"; not a std::string?

A string literal has type const char[3], and auto deduces const char* from it. Use std::string s = "hi"; or auto s = "hi"s; (C++14, with using namespace std::string_literals;).

When should a function take std::string_view instead of const std::string&?

When it only reads the text and does not need to store it or call functions that require a null-terminated string. string_view accepts literals and parts of strings without any copy. It is not guaranteed to be null-terminated, so do not pass sv.data() to C functions expecting a C-string.

In Simple Words

Use std::string for text in C++. It knows its own length, grows automatically, and supports =, + and == on the contents. C-style strings are char arrays ending in '\0', and are mainly needed to talk to C code.

  • cin >> reads one word; getline reads a line; use std::ws when mixing them.

  • find returns npos when nothing is found; always check it.

  • [] is unchecked, at() throws on a bad index.

  • "a" + "b" does not compile; one side must be a std::string.

  • std::string_view (C++17) is a cheap read-only view, but it must not outlive the text it views.