String Basics

Joining strings

Use + to join (concatenate) strings, and += to add to the end of one:

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

int main() {
    string first = "Ada";
    string last = "Lovelace";
    string full = first + " " + last;
    cout << full << "\n";

    string message = "Hello";
    message += ", World";
    message += '!';               // a single char works too
    cout << message << "\n";
    return 0;
}

Output

Ada Lovelace
Hello, World!

Length

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

int main() {
    string word = "programming";
    cout << word << " has " << word.length() << " letters\n";
    string empty = "";
    cout << "Empty? " << empty.empty() << "\n";
    return 0;
}

Output

programming has 11 letters
Empty? 1

Tip: s.size() does exactly the same as s.length().

Each character has an index

A string is a row of chars. Just like a vector, index 0 is the first one:

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

int main() {
    string city = "Paris";
    cout << city[0] << "\n";                    // P
    cout << city[city.length() - 1] << "\n";    // s (the last one)
    city[0] = 'B';
    cout << city << "\n";
    return 0;
}

Output

P
s
Baris

Think of it like this: A string is like a necklace of beads, and each bead is one letter. You can look at, or swap, any single bead by its position.

Looping over the letters

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

int main() {
    string word = "banana";
    int count = 0;
    for (char c : word) {
        if (c == 'a') count++;
    }
    cout << "'a' appears " << count << " times\n";
    return 0;
}

Output

'a' appears 3 times

Common mistake: "Hi" + " there" (two plain quoted texts) does not compile. At least one side of + must be a string variable: string("Hi") + " there" works.

HOME LABS COMMUNITY DASHBOARD