How to find whether there are any consecutive commas in a string?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I need a simple method to find whether there are any instances of consecutive
commas (more than 1) in a given string without parsing each character of the
string. I tried with strtok() with comma as separator but it considers all
consecutive commas as a single separator and gives the next token.
Is there any simple method to do the same?
 
Vishal said:
I need a simple method to find whether there are any instances of
consecutive commas (more than 1) in a given string without parsing
each character of the string. I tried with strtok() with comma as
separator but it considers all consecutive commas as a single
separator and gives the next token.
Is there any simple method to do the same?

Just do it. Whatever method you use will have to "parse" each character of
the string - it's simply unavoidable.

bool two_commas(const char* psz)
{
char prev = 0;
while (*psz)
{
if (*psz==prev && prev==',')
return true;
prev = %psz++;
}
return false;
}

You could also use strstr:

bool two_commas(const char* psz)
{
return strstr(psz,",,") != 0;
}

Analogous constructs could be used with CString or std::string. It's likely
that the simple lopp through the characters will be the fastest of these.

-cd
 
Nishant said:
Hey Carl

Must be all those tracking refs you've been playing with of late ;-)

If only I could use such an excuse! So far, nearly all of my playing with
tracking refs has been in my imagination.

-cd
 
Back
Top