C++ by Example
C++ by Example

Strings

2 min read

Strings

C++ has two string representations: C-style null-terminated char arrays (from C) and std::string from the standard library. Use std::string in all new code.

std::string basics

#include <iostream>
#include <string>

int main() {
    std::string name = "Alice";
    std::string greeting = "Hello, " + name + "!";

    std::cout << greeting          << "\n";   // Hello, Alice!
    std::cout << greeting.size()   << "\n";   // 13
    std::cout << greeting.length() << "\n";   // 13 (same as size)
    std::cout << greeting.empty()  << "\n";   // 0 (not empty)
}

Accessing characters

std::string s = "hello";

std::cout << s[0]      << "\n";   // h  — no bounds check
std::cout << s.at(4)   << "\n";   // o  — throws if out of range
std::cout << s.front() << "\n";   // h
std::cout << s.back()  << "\n";   // o

s[0] = 'H';   // strings are mutable

Common operations

#include <string>
#include <iostream>

int main() {
    std::string s = "Hello, World!";

    // Substring: substr(position, length)
    std::cout << s.substr(7, 5) << "\n";   // World

    // Find: returns index, or std::string::npos if absent
    size_t pos = s.find("World");
    if (pos != std::string::npos) std::cout << "at " << pos << "\n";   // at 7

    // Replace
    s.replace(7, 5, "C++");
    std::cout << s << "\n";   // Hello, C++!

    // Erase
    s.erase(5, 1);            // remove the comma
    std::cout << s << "\n";   // Hello C++!

    // Append
    s += " (2024)";
    std::cout << s << "\n";   // Hello C++! (2024)
}

Converting between strings and numbers

#include <string>
#include <iostream>

int main() {
    // Number → string
    std::string s = std::to_string(42);
    std::cout << s << "\n";           // "42"

    // String → number
    int    i = std::stoi("123");
    long   l = std::stol("9999999");
    double d = std::stod("3.14");
    std::cout << i << " " << d << "\n";
}

Reading input

>> reads one whitespace-delimited token. std::getline reads a full line:

#include <iostream>
#include <string>

int main() {
    std::string word, line;

    std::cout << "Enter a word: ";
    std::cin >> word;

    std::cin.ignore();   // discard the newline left by >>

    std::cout << "Enter a line: ";
    std::getline(std::cin, line);

    std::cout << word << " | " << line << "\n";
}

std::string_view (C++17)

std::string_view is a non-owning view into a string — it stores a pointer and a length without allocating. Use it in function parameters to avoid unnecessary copies:

#include <string_view>

void print(std::string_view sv) {        // works with std::string, const char*, string literals
    std::cout << sv << "\n";
}

print("hello");                          // no allocation
print(std::string("world"));             // no copy

Never store a string_view that outlives the string it points to.

Comparing strings

std::string a = "apple", b = "banana";

if (a == b)  { /* equal */ }
if (a != b)  { /* not equal */ }
if (a < b)   { /* lexicographic order */ }

// Case-insensitive compare (manual)
#include <algorithm>
#include <cctype>

auto to_lower = [](std::string s) {
    std::transform(s.begin(), s.end(), s.begin(), ::tolower);
    return s;
};
bool eq = to_lower(a) == to_lower(b);
C++ by Example
C++ by Example

Learn modern C++ through working code. Each chapter introduces one concept — variables, functions, classes, templates, smart pointers, concurrency — with a clear example, a line-by-line explanation, and notes on how it applies in real programs.

View book →