All lessons
LESSON 18/53Text and Array
Working with Text
GOALFind a word's length, join words, and reach single letters.

A string is a row of letters. They are numbered from 0 — the first letter is number 0, not 1!
ON THIS PAGE
SHOW EXAMPLE IN
//THE EXAMPLE
main.cpp
#include <iostream>
using namespace std;
int main() {
string name = "Bat";
cout << name.length() << endl; // 3
cout << name[0] << endl; // B
cout << name + "aa" << endl; // Bataa
for (int i = 0; i < name.length(); i++) {
cout << name[i] << "-";
}
cout << endl;
return 0;
}> what you see
3 B Bataa B-a-t-
//LINE BY LINE
Watch it run
s = hello. Five characters side by side, numbered from 0.
Joining strings
Use + to join two strings. You cannot join a number directly — convert it first.
string first = "Bat";
string last = "Erdene";
string full = first + " " + last;
cout << full << endl;> what you see
Bat Erdene
Reaching each character
Characters are numbered from 0. s[0] is the first character and s.size() is the length.
string s = "hello";
cout << s[0] << endl; // h
cout << s.size() << endl; // 5
for (int i = 0; i < s.size(); i++) {
cout << s[i] << "-";
}> what you see
h 5 h-e-l-l-o-