Summary: In this tutorial, we will learn different ways to find the length of a string in C++.

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.

Method 1: Length of String Object using size()

#include <iostream>
using namespace std;
 
int main()
{
    string str = "Pencil Programmer";
    cout << "Length: " << str.size();
    return 0;
}

Output:

length: 17

Method 2: Length of String Object using length()

#include <iostream>
using namespace std;
 
int main()
{
    string str = "Programming Simplified";
    cout << "Length: " << str.length();
    return 0;
}

Output:

length: 22

Method 3: Length of C-style string using strlen()

For C-style string (string formed using char array), we can use the strlen() function method to get the length of the string.

Make sure you include the library before using this function.

#include <iostream>
#include <cstring>
 
using namespace std;
 
int main()
{
    char str[] = "Pencil Programmer";
    cout << "Length: " << strlen(str);
    return 0;
}

Output:

length: 17

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

The sizeof() function in C++ returns the size of string or array in terms of bytes i.e. number of characters * size of char.

We can divide the result by sizeof(str[0]) (i.e. size of a single character) to get the actual length of the string.

But wait, string formed using char array ends with ‘\0’, which is an extra character included in the length.

Therefore we have to deduct 1 from the final result to get the true length of the string.

#include <iostream>
using namespace std;
 
int main()
{
    char str[] = "Pencil Programmer";
    int length = sizeof(str)/sizeof(str[0]) -1;
    cout << "Length: " << length;
    return 0;
}

Output:

length: 17

These are few ways using which we can find the length of the string in the C++ programming language.

Leave a Reply