Count number of characters in a string array in C++

This tutorial will discuss about unique ways to count number of characters in a string array in C++.

Suppose we have a string array, like this,

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

Now we want to count the total number of characters in this string array. For that, we need to iterate over all string objects in this array, and count number of characters in each string. Then we will add all these counts to get the total count of characters. Like this,

int count = 0;

// Get count of all characters in all
// of the strings in array
std::for_each(
        std::begin(arr),
        std::end(arr),
        [&](auto& str){
            count += str.size();
        });

We created a variable count, to store the total number of characters. Then we used the STL Algorithm std::for_each() to iterate over all strings in array, and on each string applied a lambda function. Inside this lambda function, we fetched the number of characters in that string, and added that to the count variable. This way, when for_each() function returns, we will have total number of characters in the count variable.

Let’s see the complete example,

#include <iostream>
#include <string>
#include <algorithm>

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

    int count = 0;

    // Get count of total characters in
    // a string array
    std::for_each(
            std::begin(arr),
            std::end(arr),
            [&](auto& str){
                count += str.size();
            });


    std::cout << "Number of characters in string array : " << count << "\n";
    return 0;
}

Output :

Number of characters in string array : 22

Summary

Today we learned about several ways to count number of characters in a string array 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