|
-
April 15th, 2010, 03:17 PM
#11
Re: counting consecutive null characters
 Originally Posted by JohnW@Wessex
That looks a bit over complicated. How about...
Code:
#include <string>
#include <algorithm>
int checkConNullBytes(const std::string &dataStream)
{
int maxCount = 0;
int count = 0;
std::string::const_iterator begin = dataStream.begin();
std::string::const_iterator end = dataStream.end();
while (begin != end)
{
if (*begin == 0)
{
++count;
maxCount = std::max(maxCount, count);
}
else
{
count = 0;
}
++begin;
}
return maxCount;
}
int main()
{
char data[] = {0, 1, 2, 3, 0, 0, 4 ,5 ,0, 0, 0, 6, 7};
std::string dataStream(data, data + 13);
int largest = checkConNullBytes(dataStream);
}
If you expect the string to have mostly 0s, you should put the std::max call in the else rather than the if (prior to resetting count). If you expect the 0s to be fairly rare, it'll be faster as-is.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|