Here's my Code to count how many times a char is repeated in a string :
int count_char(string a, char b)
{
int size = sizeof(a) / sizeof(a[0]);
int counter = 0;
for (int i = 0; i < size; i++)
{
if (a[i] == b)
{
counter++;
}
}
cout << a << "has " << counter << b << "s\n";
return counter;
}
int main()
{
count_char("Hello", 'l');
}
For me , everything looks good but Microsoft Visual Studio seems to see something else , this is what I got:
Can anyone see where's the problem ?
The sizeof
trick you are trying to use works only on a fixed-size array, not on a std::string
object.
std::string
has several data members, including the data pointer, the length and capacity counters, the SSO buffer (if there is one), etc. Your character data contains only 5 characters, but the size of the std::string
class is much more than that, hense why you are going out of bounds on the iteration.
To get the correct character size, use the string's size()
(or length()
) method instead:
size_t size = a.size(); // or .length()
That being said, you don't need to count the characters manually. You can use the standard std::count()
algorithm instead:
#include <algorithm>
size_t counter = std::count(a.begin(), a.end(), b);