Skip to content
C++

Strings

std::string operations.

By EZ4Code Team
stringstring

Code

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

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

    // Length and access
    std::cout << s.length() << "\n";
    std::cout << s[0] << s.at(1) << "\n";

    // Find
    size_t pos = s.find("World");
    if (pos != std::string::npos)
        std::cout << "found at " << pos << "\n";

    // Substring
    std::string sub = s.substr(7, 5); // "World"

    // Concatenate
    std::string s2 = s + " Goodbye";
    s2.append("!");

    // Replace
    s2.replace(7, 5, "C++");

    // Insert and delete
    std::string s3 = "Hello";
    s3.insert(5, " World");
    s3.erase(5, 6);

    // Convert
    std::string upper = s;
    std::transform(upper.begin(), upper.end(), upper.begin(), ::toupper);
    std::string lower = s;
    std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower);

    // Split
    std::stringstream ss("a,b,c,d");
    std::string token;
    while (std::getline(ss, token, ',')) {
        std::cout << token << " ";
    }
    std::cout << "\n";

    // Number-string conversion
    int n = std::stoi("42");
    double d = std::stod("3.14");
    std::string str = std::to_string(123);

    return 0;
}

Explanation

std::string provides rich string operations, including find, replace, concatenate, convert, and split.

More C++ Snippets