Lesson 5 of 25

Strings

C++ Strings

C++ has two types of strings: C-style char arrays and the modern std::string class. Always prefer std::string.

Example
#include <string>
using namespace std;

// std::string
string name = "Alice";
string greeting = "Hello, " + name; // concatenation

// String methods
cout << name.length() << endl;     // 5
cout << name.at(0) << endl;        // 'A'
cout << name.substr(0, 3) << endl; // "Ali"
cout << name.find("ice") << endl;  // 2

name.append(" Smith");   // "Alice Smith"
name.insert(5, " J.");   // "Alice J. Smith"
name.erase(5, 3);        // "Alice Smith"
name.replace(6, 5, "Jones"); // "Alice Jones"

// Comparison
string a = "apple", b = "banana";
if (a < b) cout << a << " comes first" << endl;
if (a == "apple") cout << "Match!" << endl;

String Input and Conversion

Reading strings from input and converting between strings and numbers.

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

int main() {
    // Input with spaces
    string fullName;
    cout << "Enter full name: ";
    getline(cin, fullName);

    // String to number
    string numStr = "42";
    int num = stoi(numStr);       // string to int
    double d = stod("3.14");     // string to double

    // Number to string
    string s = to_string(42);    // "42"
    string s2 = to_string(3.14); // "3.140000"

    return 0;
}