Get Length of a string in C++

This tutorial will discuss about a unique way to get length of a string in C++.

The string class in C++, provides a function size() i.e.

std::size_t std::string::size() const

It returns the number of characters in the string. But,It does not includes the count of null-terminating character.

For example, if our string is “Sample Text”, like this,

std::string strValue = "Sample Text";

Then the strValue.size() will return the value 11 as the size, which is the number of characters in the string.

Let’s see the complete example,

#include <iostream>
#include <string>

int main()
{
    std::string strValue = "Sample Text";

    // Get number of characters in string
    size_t len = strValue.size();

    std::cout << "Length of the string is: " << len << "\n";

    return 0;
}

Output :

Length of the string is: 11

Summary

Today we learned about several ways to get length of a string in C++. Thanks.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top