Start learning free

LESSON 268 OF 667 · STRINGS

Strings in C++

Lesson

The C++ string is an object that represents a sequence of characters, each identified by one index.

Creation:

To create strings in C++, you use double quotes like this:

string greeting = "Hello";

Accessing characters:

To access the characters in a string, you use the [] operator

The following example returns the first character of a string with the index zero:

string str = "Hello";
char ch = str[0];
// ch is 'H'

Getting the length:

We can get the length of a string using the size() method.

For example, to access the last character of the string, you use the size() - 1 index:

string str = "Hello";
char ch = str[str.size() - 1]; 
// ch is 'o'

Concatenating strings via + operator:

To concatenate two or more strings, you use the + operator:

string name = "John";
string str = "Hello " + name;

cout << str << endl; // prints "Hello John"

If you want to assemble a string piece by piece, you can use the += operator:

string greet = "Welcome";
string name = "John";
greet += " to AlgoCademy, ";
greet += name;

cout << greet << endl; // prints "Welcome to AlgoCademy, John"

String slicing

We often want to get a substring of a string. For this, we use the substr() method.

substr(startIndex, length) returns the substring starting from startIndex and taking length characters:

string str = "JavaScript";
string substr = str.substr(2, 4);

cout << substr << endl; // prints "vaSc"

The startIndex is a zero-based index at which the substr() starts extraction.

The length parameter specifies how many characters to extract from the starting position.

If you omit the length parameter, the substr() extracts to the end of the string:

string str = "JavaScript";
string substr = str.substr(4);

cout << substr << endl; // prints "Script"

Iterating through the characters:

We can iterate through the characters of a string using a for loop and the : operator like this:

string myStr = "Andy";
for (char c : myStr) {
    cout << c << endl;
}

// This will print the characters 'A', 'n', 'd' and 'y' on different lines

We can also iterate through the elements of a string using indices and a for loop like this:

string myStr = "Andy";
for (int i = 0; i < myStr.size(); i++) {
    cout << myStr[i] << endl;
}

// This will print the characters 'A', 'n', 'd' and 'y' on different lines

Both ways take O(n) time, where n is the length of the string we iterate on.


Assignment
Follow the Coding Tutorial and let's play with some strings.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 5
    Ctrl + Enter to check