Strings

You have used string since the Data Types lesson to store text. A string can do more than hold text. You can join strings, ask for their length, and read or change single characters.

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

int main() {
    string first = "Ada";
    string last = "Lovelace";
    string full = first + " " + last;
    cout << full << "\n";
    cout << full.length() << "\n";
    return 0;
}

Output:

Ada Lovelace
12

+ joins strings. This is called concatenation. Notice the " " in the middle. + adds nothing on its own, so if you want a space between the names, you must add it yourself.

.length() counts the characters. Ada Lovelace has 12 characters, and the space counts too. The dot means that length() is a function that belongs to the string. You call it on one string, full, and it answers for that string. You will see this "value, dot, function" form a lot from now on.

One character at a time

A string is a row of characters, a bit like an array of char. So you can use an index in square brackets, starting at 0:

string name = "Ada";
cout << name[0] << "\n";
name[0] = 'E';
cout << name << "\n";

Output:

A
Eda

name[0] is the first character, A. Assigning 'E' to it changes the string to Eda. Use single quotes here, because one character is a char. Just like with arrays, C++ does not check this index, so stay between 0 and the length minus 1.

Comparing strings

== checks if two strings have exactly the same text. < checks which one comes first, almost like in a dictionary:

string a = "apple";
cout << (a == "apple") << "\n";
cout << (a < "banana") << "\n";
cout << ("Zebra" < a) << "\n";

Output:

1
1
1

All three comparisons are true, so each line prints 1. The last one may surprise you. C++ compares the characters by their codes, and all uppercase letters come before all lowercase letters. So "Zebra" comes before "apple".

Joining two pieces of quoted text

+ needs a string on at least one side. Two pieces of quoted text, like "Hello, " + "Ada", are not string variables, so you cannot join them:

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

int main() {
    string greeting = "Hello, " + "Ada";
    cout << greeting << "\n";
    return 0;
}

Output:

main.cpp: In function ‘int main()’:
main.cpp:6:33: error: invalid operands of types ‘const char [8]’ and ‘const char [4]’ to binary ‘operator+’

The compiler does not see a string on either side of +. It sees two pieces of quoted text, which it calls const char [8] and const char [4]: rows of characters, not strings. (Each one has a hidden end marker, so the size is one more than the number of characters.) The compiler cannot add those. Put the text in a string variable first, or write it as one piece: "Hello, Ada".

In the exercise, read a first name and a last name, join them with a space, and print the full name and its length.