We are committed to provide service 24 X 7

Deals, Shopping, Training, Tools

21
599.835,50

Cart

Quantity 11.444,40

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++.

Advertisements

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.

21
599.835,50

Cart

Quantity 11.444,40