Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to find number of elements in an array of strings in c++?

Tags:

c++

i have an array of string.

std::string str[10] = {"one","two"}

How to find how many strings are present inside the str[] array?? Is there any standard function?

like image 748
SPB Avatar asked Dec 07 '22 22:12

SPB


1 Answers

There are ten strings in there despite the fact that you have only initialised two of them:

#include <iostream>
int main (void) {
    std::string str[10] = {"one","two"};
    std::cout << sizeof(str)/sizeof(*str) << std::endl;
    std::cout << str[0] << std::endl;
    std::cout << str[1] << std::endl;
    std::cout << str[2] << std::endl;
    std::cout << "===" << std::endl;
    return 0;
}

The output is:

10
one
two

===

If you want to count the non-empty strings:

#include <iostream>
int main (void) {
    std::string str[10] = {"one","two"};
    size_t count = 0;
    for (size_t i = 0; i < sizeof(str)/sizeof(*str); i++)
        if (str[i] != "")
            count++;
    std::cout << count << std::endl;
    return 0;
}

This outputs 2 as expected.

like image 112
paxdiablo Avatar answered Mar 06 '23 09:03

paxdiablo