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?
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.
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 .
words[j]. length() will give you the length of the string in index j of your array.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With