Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count strings in string array c++?

Tags:

c++

string

count

How to sum number of strings in string array in which is not explicit defined how many elements it takes?

string str[] = { "astring", "bstring", "cstring", "dstring", "zstring" };

Need to find out how many elements array have?

like image 533
tonni Avatar asked Oct 24 '12 12:10

tonni


People also ask

How do you count strings in an array?

Approach: The idea is to iterate over all the strings and find the distinct characters of the string, If the count of the distinct characters in the string is less than or equal to the given value of the M, then increment the count by 1.

How do you count the number of times a string appears in an array?

To check how many times an element appears in an array:Declare a count variable and set its value to 0 . Use the forEach() method to iterate over the array. Check if the current element is equal to the specific value. If the condition is met, increment the count by 1 .

How do I find a character in an array of strings?

words[j]. length() will give you the length of the string in index j of your array.


2 Answers

template< typename T, size_t N >
/*constexpr*/ size_t size( T(&arr)[N]) )
{
   return N;
}

constexpr if available (C++11) will allow you to use the return value for static (compile time) usage as a size of another array.

like image 126
CashCow Avatar answered Sep 28 '22 20:09

CashCow


If str[] is statically defined (as shown), then this will work:

const size_t numElements = sizeof(str) / sizeof(str[0]);

If it's dynamically created, then you are going to need a marker to signal the last element (0 is being typically used if it's an array of pointers). Either that or the caller tells you how many elements there are (also common).

like image 37
trojanfoe Avatar answered Sep 28 '22 21:09

trojanfoe