C++ · Module 3 · Lesson 51 min read

std::string Basics

Creating strings (<string>)

c
std::string a = "Hello";
std::string b{"World"};
std::string empty;              // ""
std::string stars(5, '*');      // "*****"

Essential operations

OperationExampleResult
Lengths.size() or s.length()number of chars
Empty?s.empty()bool
Concatenatea + " " + bnew string
Appends += "!"; s.push_back('x');modifies s
Accesss[0], s.at(0), s.front(), s.back()char
Compare==, !=, <, >alphabetical (case-sensitive)
Substrings.substr(pos, len)new string
Finds.find("lo")index or std::string::npos
Insert / erases.insert(5, "!!"), s.erase(0, 2)modifies s
Replaces.replace(pos, len, "new")modifies s
Clears.clear()""

s[i] vs s.at(i)

  • s[i]: no bounds check (fast; out of range = undefined behaviour)
  • s.at(i): checks and throws std::out_of_range ✅ safer while learning

Finding things

c
auto pos = email.find('@');
if (pos != std::string::npos) { ... }   // found

npos is a special value meaning "not found".

Looping over characters

CSS
for (char c : s) { ... }
for (std::size_t i = 0; i < s.size(); ++i) { ... }

Comparison

Strings compare lexicographically (dictionary order by character code): "apple" < "banana", but "Zebra" < "apple" (uppercase letters come first in ASCII).

C++20 helpers

s.starts_with("http"), s.ends_with(".cpp"); C++23 adds s.contains("x").

Example

C++
#include <iostream>
#include <string>

int main() {
    std::string first = "Asha", last{"Sharma"};
    std::string full = first + " " + last;
    std::cout << full << " has " << full.size() << " characters\n";

    std::string email = "asha.sharma@example.com";
    auto at = email.find('@');
    if (at != std::string::npos) {
        std::cout << "user: " << email.substr(0, at) << ", domain: " << email.substr(at + 1) << '\n';
    }
    std::cout << "find(\"xyz\") == npos ? " << std::boolalpha << (email.find("xyz") == std::string::npos) << '\n';

    std::string msg = "Track your money";
    msg += "!";
    msg.insert(0, ">> ");
    msg.replace(msg.find("money"), 5, "expenses");
    std::cout << msg << '\n';
    std::cout << "first: '" << msg.front() << "', last: '" << msg.back() << "', at(3): '" << msg.at(3) << "'\n";

    int vowels = 0;
    for (char c : msg)
        if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') vowels++;
    std::cout << "vowels: " << vowels << '\n';

    std::cout << "\"apple\" < \"banana\": " << (std::string("apple") < "banana") << '\n';
    std::cout << "\"Zebra\" < \"apple\": " << (std::string("Zebra") < "apple") << '\n';

    std::string file = "budget.cpp";
    std::cout << "ends with .cpp? " << file.ends_with(".cpp") << ", starts with bud? " << file.starts_with("bud") << '\n';
    std::cout << std::string(20, '=') << '\n';
    return 0;
}

/* Output:
Asha Sharma has 11 characters
user: asha.sharma, domain: example.com
find("xyz") == npos ? true
>> Track your expenses!
first: '>', last: '!', at(3): 'T'
vowels: 6
"apple" < "banana": true
"Zebra" < "apple": true
ends with .cpp? true, starts with bud? true
====================
*/