tags:

views:

246

answers:

2

The definition of library function strspn is:

size_t strspn(const char *str, const char *chars)

/*Return number of leading characters at the beginning of the string str which are all members of string chars.*/

e.g. if ‘str’ is “fecxdy” and ‘chars’ is “abcdef” then the function would return 3, since ‘f’, ’e’ and ‘c’ all appear somewhere in ‘chars’, giving 3 leading characters of ‘str’, and ‘x’ is the first character of ‘str’ which is not a member of ‘chars’.

Could someone help me write an implementation of strspn in ‘C’. The only library function I am allowed to call from the implementation is strlen.

+4  A: 

The basic idea is to step through the string, one character at a time, and test if it's in the character set. If it's not, stop and return the answer. In pseudocode, that would look like:

count = 0
for each character c in str
    if c is not in chars
        break
    count++
return count

The if c is not in chars test can be implemented by iterating through all of the characters of chars and testing if c matches any of the characters. Note that this is not the fastest implementation, since it involves stepping through the chars string for each character in str. A faster implementation would use a lookup table to test if c is not in chars.

Adam Rosenfield
+1  A: 

Without touching a C-compiler for the last couple of years. From the top of my head something like this should work:

int spn = 0;
while(*str++ != '\0')
{
  char *hay = chars;
  bool match = false;
  while(*hay++ != '\0')
  {
     if(*hay == *str)
     {
       match = true;
       break;
     }
  }

  if(match)
     spn++;
  else
     return spn;
}
return spn;
John Nilsson