In this tutorial, we will learn how to find the length of a string in C++ using different techniques.

In C++, can write string either as string object or as char array (also known as C style string).

For string object, we can use size() or length() method to get the length of the string and for C-type string we can use strlen() or sizeof() function.

Let’s see an example of each.

Example 1: length of String Object using size()


Example 2: length of String Object using length()


Example 3: length of C-style string using strlen()

For C-style string (string formed using char array), we can use strlen() function. Make sure you include library before using this function.


Example 4: Length of C-Style string using sizeof()

sizeof() function in C++ returns the size of string or array in terms of bytes. So if we use use sizeof(str) it will return number of characters * size of char.

We can divide the result by sizeof(str[0]) i.e size of single character, to get the number of characters in the string.

But wait, string formed using char array ends with ‘\0’, which is an extra character included in the length. Therefore we need to deduct 1 from out final result to get the true length of the string.


Comment below if you have any suggestions or doubts.

Leave a Reply