Strings and Methods of Strings

String is a primitive data type which is used to store text or sequence of characters. Strings are always enclosed in double quotation marks. String is an array of characters. We will discuss arrays later on.

Header file of string

Concatenation

Concatenation means joining of two strings and it is achieved by using addition "+" operator.

Note: If you have numbers in your string, they will not sum up, rather they will be concatenated.

String Length

Length of string can be found by using ".length()" or ".size()" method.

Accessing Characters in String

As we have previously discussed that string is a sequence of characters. So, we can access individual character, and we can also reassign them some other values.

Note: If you want to print double quotes inside string, use \"

Inputs in String

There are two methods of taking inputs in string.

Methods of Strings

In C++, we have to include a header file of string, #include

MethodDescriptionCode
length()int length = text.length();It is used to calculate the length of a string variable.
append(x)str1.append(str2);It is used to append strings.
substr(x, y)string sub = text.substr(0, 5);It is used to find a substring in a string.
replace(x, y, z)text.replace(7, 5, "Universe");It will replace characters from starting index to ending index with the given string.
erase(x, y)text.erase(7, 4);It will remove characters from starting index to ending index.
find(x, y)text.erase(7, 4);It will search for the first occurrence of the specified substring within the string, starting from the given position.

Practice Exercises

Complete these exercises to reinforce your learning and earn XP

Sign in to track your progress and earn XP!
Exercise 1 of 2Medium

How are strings terminated in C?

15 XP~3 min
Exercise 2 of 2Easy

To find the length of a string, we use the ___ function.

10 XP~2 min