In this tutorial you shall learn how to use
1. String Data Type
You should immediately notice that the declaration and assignment of a string is similar to int and doubles which you learned previously.
Declaring and Initializing the String
First make sure you have the appropriate headers in the file where you plan to use string objects.
#include
using namespace std;
How to declare and initialize strings:
string student = "Diego"; // Declare and initialize to Diego
student = "Talk Binary"; //Assign student to Talk Binary
Notice how strings are encapsulated within “””s. If used without them, it would mean you would want to assign the value of that variable of that name to your string variable.
From the terminal…
cin >> student; //Reads up to the space
getline(cin, student); //Reads up to pressed Enter
You may also concatenate strings
string first = "Talk";
string last = "Binary";
string name = first + " " + last; //What happens if we exclude the " " ?
cout << name; //Outputs Talk Binary.
Substrings
We can find the length of a string using the length() function and also print out a substring from a string.
string name = "Talk Binary";
cout << name.length() << endl; //Outputs 11 (Counts the space as a character).
cout << name.substr(3,5); //Starts at position 3, and prints 5 characters "k Bin"
The position is determined as follows.

You may also use the following...
cout << name[3]; //Will output the character in position 3.
Remember, the best way to learn something, is to practice! Therefore, start practicing!
Programming Challenges
Using what we know, we'll make a small program.
1. Read in a first name, and last name, and assign them to a first and last string variable respectively.
- a. Find the length of both and assign their lengths to two different int variables respectively.
- b. Concatenate the first and last name into one string variable.
- c. Using the substr function, and your two int variables holding length, extract the first and last name from your last string variable that has the first and last name concatenated.
If you have any questions, comments, or concerns please comment below!
