Cppstd::string

std::string

std::string, defined in the <string> header, is the string type used throughout modern C++. It manages its own memory automatically, tracks its own length, and supports natural operators like + and == — solving nearly every pain point of C-style character arrays from the previous chapter.
Creating and initializing strings

string_basics.cpp

CPP
#include <iostream>
#include <string>

int main() {
    std::string empty;                    // ""
    std::string greeting = "Hello";       // from a string literal
    std::string copy(greeting);           // copy constructor
    std::string repeated(3, 'x');         // "xxx"

    std::cout << greeting << std::endl;
    std::cout << repeated << std::endl;

    return 0;
}
Concatenation with +

string_concat.cpp

CPP
#include <iostream>
#include <string>

int main() {
    std::string first = "Hello";
    std::string second = "World";

    std::string message = first + ", " + second + "!";
    std::cout << message << std::endl;   // Hello, World!

    message += " Nice to meet you.";     // append in place
    std::cout << message << std::endl;

    return 0;
}
Common member functions

Method

Purpose

.length() / .size()

Number of characters in the string (identical results)

.substr(pos, len)

Returns a new string starting at pos, up to len characters

.find(text)

Returns the index of the first match, or std::string::npos if not found

.append(text)

Adds text to the end (similar to +=)

.replace(pos, len, text)

Replaces len characters starting at pos with text

.empty()

Returns true if the string has zero length

.c_str()

Returns a const char* for interfacing with C APIs

string_methods.cpp

CPP
#include <iostream>
#include <string>

int main() {
    std::string text = "Learning C++ is fun";

    std::cout << text.length() << std::endl;        // 20
    std::cout << text.substr(9, 3) << std::endl;     // "C++"

    std::size_t pos = text.find("fun");
    if (pos != std::string::npos) {
        std::cout << "Found at index " << pos << std::endl;
    }

    text.replace(0, 8, "Mastering");
    std::cout << text << std::endl;    // "Mastering C++ is fun"

    std::cout << std::boolalpha << text.empty() << std::endl;  // false

    // c_str() for legacy C functions that expect a const char*
    printf("%s\n", text.c_str());

    return 0;
}
Comparing strings
Unlike C-style strings, which require calling strcmp, std::string overloads the comparison operators directly, so comparisons read naturally.

string_compare.cpp

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

if (a == "apple") { /* true */ }
if (a != b)        { /* true */ }
if (a < b)          { /* true — lexicographic comparison */ }
Converting between numbers and strings

string_conversions.cpp

CPP
#include <iostream>
#include <string>

int main() {
    int age = 30;
    std::string ageText = std::to_string(age);       // "30"
    std::cout << "I am " + ageText + " years old" << std::endl;

    std::string numberText = "123";
    int parsed = std::stoi(numberText);              // 123 (string to int)

    std::string decimalText = "3.14";
    double pi = std::stod(decimalText);               // 3.14 (string to double)

    std::cout << parsed + 1 << std::endl;
    std::cout << pi * 2 << std::endl;

    return 0;
}
String streams
std::stringstream, from the <sstream> header, treats a string like an input/output stream — useful for parsing multiple values out of one string, or building a complex string piece by piece.

string_stream.cpp

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

int main() {
    std::stringstream ss("25 3.5 hello");

    int intValue;
    double doubleValue;
    std::string wordValue;

    ss >> intValue >> doubleValue >> wordValue;

    std::cout << intValue << " " << doubleValue << " " << wordValue << std::endl;

    // Building a string
    std::stringstream builder;
    builder << "x = " << 10 << ", y = " << 20;
    std::cout << builder.str() << std::endl;

    return 0;
}
  • Prefer std::string over C-style arrays for essentially all new code — it is safer and easier to use correctly.

  • .c_str() is your bridge to C — use it only when a function specifically requires a const char*.

  • .find() returns std::string::npos, not -1, when nothing is found — comparing against -1 is a common bug.

Performance note
std::string typically allocates memory on the heap for anything beyond a small number of characters (implementations vary, many use “small string optimization” to avoid heap allocation for very short strings). It is not free, but the safety and convenience it buys is almost always worth it.