Thuta Learning
BasicProgrammingbeginner

Strings

Relax. We'll talk through this in plain words — no textbook voice.

Strings are used to store text. You can handle text data like user names, titles, messages, addresses, and product names with string. To use string in C++, it's safer to include the <string> header.

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

int main() {
    string firstName = "Sai";
    string lastName = "Tun";
    string fullName = firstName + " " + lastName;

    cout << "Full name: " << fullName << endl;
    cout << "Length: " << fullName.length() << endl;
    cout << "First letter: " << fullName[0];
    return 0;
}

+ can be used to join strings together. length() returns how many characters are in the string. fullName[0] gets the first character. Keep in mind that indexing starts at 0.

You should see
Full name: Sai Tun Length: 7 First letter: S

Info

String indexing is 0-based. The first character is index 0, the second is index 1.

Easy traps

  • Accessing an index that doesn't exist, like fullName[100], can cause unexpected behavior. Checking the string's length first is the safer approach.