C++ Program to find the length of a string


January 19, 2023, Learn eTutorial
998

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. In this C++ program, we need to find the length of the string

How to find the length of a string using C++?

C++ has length() and size() function. These can be used to get the length of a string-type object. This function is used to return the length of the string in terms of bytes. It gives the number of bytes aligned to form the string.

Syntax: Consider a string object named 'str'. To calculate the size of this string object, its syntax would be : str.size() 

Parameters: This function does not contain any parameters.
Return Value: size() function returns the number of characters or the bytes in the string.

Algorithm 

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;
}
                                      

OUTPUT

String Length = 26