Get string array length in C++

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

To get the length of an array of strings, we need to count the number of elements in the array. For that we can use the sizeof operator. Like this,

std::string arr[] = {"First", "Second", "Third", "Fourth"};

// Get the length of array
size_t len = sizeof(arr) / sizeof(arr[0]);

The sizeof(arr) operator will give us the total size of array, then we can divide it by the size of first element of array i.e. sizeof(arr[0]). It will give us the total number of elements in array. So, this way we can get the length of a string array in C++.

Let’s see the complete example,

#include <iostream>

int main()
{
    std::string arr[] = {"First", "Second", "Third", "Fourth"};

    // Get the length of array
    size_t len = sizeof(arr) / sizeof(arr[0]);

    std::cout << "Length of string array is : " << len << std::endl;

    return 0;
}

Output :

Length of string array is : 4

Summary

Today we learned about several ways to get string array length 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