</>
Skip to content
C++ lessons (11/42)

C++ — Strings

Creating strings

#include <iostream>
#include <string>
using namespace std;

int main() {
    string s1 = "Hello";
    string s2("World");
    string s3(5, 'A');           // "AAAAA"
    string s4 = s1 + " " + s2;  // "Hello World"

    cout << s4 << endl;
    cout << "Length: " << s4.length() << endl;
    return 0;
}

String operations

#include <iostream>
#include <string>
using namespace std;

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

    // Access characters
    cout << s[0] << endl;       // H
    cout << s.at(7) << endl;    // W (bounds-checked)

    // Substrings
    cout << s.substr(0, 5) << endl;   // Hello
    cout << s.substr(7) << endl;      // World!

    // Find
    size_t pos = s.find("World");
    if (pos != string::npos) {
        cout << "Found at: " << pos << endl; // 7
    }

    // Replace
    string s2 = s;
    s2.replace(7, 5, "C++");
    cout << s2 << endl; // Hello, C++!

    // Insert and erase
    s2.insert(7, "Modern ");
    cout << s2 << endl; // Hello, Modern C++!
    s2.erase(7, 7);
    cout << s2 << endl; // Hello, C++!

    return 0;
}

String comparison

#include <iostream>
#include <string>
using namespace std;

int main() {
    string a = "Apple";
    string b = "Banana";

    if (a < b) {
        cout << a << " comes before " << b << endl;
    }

    cout << "Compare: " << a.compare(b) << endl; // Negative

    // Case-insensitive comparison
    string s1 = "Hello";
    string s2 = "hello";
    bool equal = (s1.size() == s2.size());
    for (size_t i = 0; i < s1.size() && equal; i++) {
        equal = (tolower(s1[i]) == tolower(s2[i]));
    }
    cout << "Case-insensitive equal: " << equal << endl;

    return 0;
}

String concatenation

#include <iostream>
#include <string>
using namespace std;

int main() {
    string result;

    // Method 1: + operator
    result = "Hello" + string(" ") + "World";

    // Method 2: += operator
    string s = "Hello";
    s += " ";
    s += "World";

    // Method 3: append
    string t = "Hello";
    t.append(" ").append("World");

    // Method 4: fmt (C++20)
    // auto msg = std::format("Name: {}, Age: {}", "Alice", 30);

    cout << result << endl;
    return 0;
}

String conversion

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main() {
    // Number to string
    int num = 42;
    string s = to_string(num);
    cout << "String: " << s << endl;

    double pi = 3.14159;
    string ps = to_string(pi);
    cout << "Pi: " << ps << endl;

    // String to number
    int n = stoi("42");
    float f = stof("3.14");
    long l = stol("1000000");
    cout << "int: " << n << ", float: " << f << endl;

    // Stringstream
    stringstream ss;
    ss << "Name: " << "Alice" << ", Age: " << 30;
    string line = ss.str();
    cout << line << endl;

    return 0;
}

String views (C++17)

Non-owning reference to a string — avoids copies:

#include <iostream>
#include <string>
#include <string_view>
using namespace std;

void printLength(string_view sv) {
    cout << "Length: " << sv.length() << endl;
}

int main() {
    string s = "Hello, World!";
    printLength(s);            // 12
    printLength("Literal");    // 7
    printLength(s.substr(0, 5)); // 5

    // string_view is lightweight
    cout << "sizeof(string): " << sizeof(string) << endl;
    cout << "sizeof(string_view): " << sizeof(string_view) << endl;

    return 0;
}

Raw strings

#include <iostream>
#include <string>
using namespace std;

int main() {
    // Raw string literal — no escape needed
    string path = R"(C:\Users\Alice\Documents)";
    cout << path << endl;

    // Multi-line raw string
    string json = R"({
    "name": "Alice",
    "age": 30
})";
    cout << json << endl;

    // Custom delimiter
    string sql = R"SQL(SELECT * FROM users WHERE id = 1)SQL";
    cout << sql << endl;

    return 0;
}

Common string algorithms

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

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

    // Transform
    string lower = s;
    transform(lower.begin(), lower.end(), lower.begin(), ::tolower);
    cout << "Lower: " << lower << endl;

    string upper = s;
    transform(upper.begin(), upper.end(), upper.begin(), ::toupper);
    cout << "Upper: " << upper << endl;

    // Reverse
    string rev = s;
    reverse(rev.begin(), rev.end());
    cout << "Reverse: " << rev << endl;

    // Sort characters
    string sorted = "dcba";
    sort(sorted.begin(), sorted.end());
    cout << "Sorted: " << sorted << endl;

    return 0;
}

Mini Practice

Write C++ code that:

  1. Creates a string and finds all occurrences of a character
  2. Reverses a string using std::reverse
  3. Converts a string to uppercase and lowercase
  4. Uses string_view to avoid copying a substring

Up Next

In the next lesson, you'll learn about If Else — conditional branching in C++.

Related Topics

Frequently Asked Questions about Strings

What is Strings in C++?

Strings is a fundamental concept in C++. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Strings?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Strings.

Why is Strings important in C++?

Strings is essential for C++ development. Understanding this concept will help you write better code and solve real-world problems more effectively.