C++ Program to find the length of a string

In this example, you will learn to compute the length ( size ) of a string.

What is the length of a string?

The length or size of a string means the total number of characters present in it. For Example, The string “learnetutorials” has 15 characters.

How do you get the length of a string in C++?

The C++ String class has length() and size() function. These can be used to get the length of a string-type object. To get the length of the traditional C-like strings, we can use the strlen() function.

C++ String size()

This function is used to return the length of the string in terms of bytes. It defines the actual number of bytes that conform to the contents of the string object which is not necessarily equal to the capacity.
Consider a string object named 'str'. To calculate the size of this string object, its syntax would be :
This function does not contain any parameters.
Return Value
This function returns the number of characters present in the string object.


Step 1:  Call the header file iostream.

Step 2: Use the namespace std.

Step 3: Open the integer type main function; int main().

Step 4: Declare string type variable str = “welcome to learnetutorials”

Step 5: Get the length of the string  by using the function str. length();

Step 6: Print the length of the string.

Step 7: Exit

C++ Source Code

                                          #include <iostream>
using namespace std;

int main() {
    string str = "Welcome to learnetutorials";

    // you can also use str.size()
    cout << "String Length = " << str.length();

    return 0;


String Length = 26