Link to home
Start Free TrialLog in
Avatar of directxBOB
directxBOBFlag for Ireland

asked on

Searching a String

Just been playing around with a few string searches.

I have just done:

int String_CountSeperators(const char *pString, int c)
{

  int count = 0;
      do
      {
                if(*pString == (char)c)
                    {
                       count++;
                     }
      }
      while(*pString++);

      return count;
}


The idea is that the user would pass in a string (*pString) and then an int (c) which is the location in that string of the first seperator. It will then search the string and count how many seperators I have, returning the count.

Does it look right? anything I could do to improve it?
Avatar of nixfreak
nixfreak

> int (c) which is the location in that string of the first seperator.

c seems to contain the value of the seperator and not its location.
nixfreak is exactly right, c is the value of the seperator...so technically instead of casting c to a char you should have the definition of the function be int (const char *, char). Where the return value is the number of occourences.
And I think you want:

while(pString++); //I dont think you want to dereference then increment!
SOLUTION
Avatar of BrianGEFF719
BrianGEFF719
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of directxBOB

ASKER

Sorry my mistake, yes I was referring to C as an Int being the location within the pString.

I'm still getting used to talking C and C++ (formerly a java programmer)
You're in good company, a lot of C runtime library functions (such as 'tolower()' etc.) take the char argument as an 'int', thus this did not seem important to me.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>>>> anything I could do to improve it?

Maybe that:
int String_CountSeperators(const char *pString, int c)
{
      int count = 0;
      while(pString = strchr(pString, c)) pString++, count++;
      return count;
}

or
 
int String_CountSeperators(const char *pString, int c)
{
     for (int count = 0; pString  != NULL; count += ((char)c == *pString++)? 1 : 0);  
     return count;
}
Some compilers need:    
     int count = 0;
     for (; pString  != NULL; count += ((char)c == *pString++)? 1 : 0);  
     return count;
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial