5

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?

3
  • Do you mean non-null, non-empty strings? No. Commented Apr 21, 2011 at 4:10
  • ya u can say that...as there are right know only 2 strings present. Commented Apr 21, 2011 at 4:16
  • You can find it at runtime. see my answer below. I wonder if it can happen at compile time. Commented Apr 21, 2011 at 5:28

8 Answers 8

7

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Ya thats true. but when i run a loop then how can i come to know that i need to loop it twice only?
You'd compare the element to the null string and thats when yous stop your loop
Don't run it twice only. Run it 10 times and skip those where the underlying string is empty.
Sorry mate. Three issues. 1. Why keep figuring out how many elements in the string Second.. What if there are 10,000,000 Order N. Really Last why not return size_t. You code could easily overrun. the count should be the same type as the for-iterator.
@baash05: (1) You can manually cache that if you like but, unless your compiler is totally brain-dead, it will already be doing that. (2) Doesn't matter. Unless you're certain all the empty strings are at the end, you have to look at every index. You can binary search if you know that fact but I'd probably just have a different class that maintained the count and adjusted it in a setter (changing non-null to null -> count--, null to non-null -> count++). (3) Yes, missed that, will change. But, if you have that many strings, you've got more problems than integer overflow :-)
6

If you want to count all elements sizeof technique will work as others pointed out. If you want to count all non-empty strings, this is one possible way by using the standard count_if function.

bool IsNotEmpty( const std::string& str )
{
    return !str.empty();
}


int main ()
{
    std::string str[10] = {"one","two"};

    int result = std::count_if(str, &str[10], IsNotEmpty);
    cout << result << endl; // it will print "2"

    return 0;
 }

1 Comment

@baash05: you could use find_if(..., IsEmpty) if you knew the first empty element delimited the in-use values.
2

I don't know that I would use an array of std::strings. If you're already using the STL, why not consider a vector or list? At least that way you could just figure it out with std::vector::size() instead of working ugly sizeof magic. Also, that sizeof magic won't work if the array is stored on the heap rather than the stack.

Just do this:

std::vector<std::string> strings(10);
strings[0] = "one";
strings[1] = "two";

std::cout << "Length = " << strings.size() << std::endl;

2 Comments

But the question is for finding the active strings in array. However vector<> would be a good idea for finding size, very straight forward.
Ah shoot gotta start reading the entire question + comments. He could always use a vector, push_back the vector with strings, and then just do vector.size(). I don't see why he would ever have inactive strings as long as he pop_back's
0

You can always use countof macro to get the number of elements, but again, the memory was allocated for 10 elements and thats the count that you'll get.

Comments

0

The ideal way to do this is

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

int num_of_elements = sizeof( str ) / sizeof( str[ 0 ] );

2 Comments

He defined the size of the array in the constructor. So while your code here would work. str[10] (as per his code) would have 10 strings. All be-it some would be empty.
That's what I meant. You don't need to supply array length all the time
0

Since you know the size. You could do a binary search for not null/empty.

str[9] is empty
str[5] is empty
str[3] is not empty
str[4] is empty
You have 4 items.

I don't really feel like implementing the code, but this would be quite quick.

1 Comment

It wouldn't work if there are empty strings in the middle of the array. We could use this if we have our own insert so we can keep the array sorted. I wouldn't do this until it becomes a real bottle-neck. :)
0

Simply use this function for 1D string array:

template<typename String, uint SIZE>  // String can be 'string' or 'const string'
unsigned int NoOfStrings (String (&arr)[SIZE])
{
  unsigned int count = 0;
  while(count < SIZE && arr[count] != "")
    count ++;
  return count;
}

Usage:

std::string s1 = {"abc", "def" };
int i = NoOfStrings(s1);  // i = 2

I am just wondering if we can write a template meta program for this ! (since everything is known at compile time)

Comments

0

A simple way to do this is to use the empty() member function of std::string like this e.g.:

    size_t stringArrSize(std::string *stringArray) {

       size_t num = 0;
       while (stringArray->empty() != true) {
           ++num;
           stringArray++;
       }
       return num;

    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.