1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Homework Help: C standard function strspn

  1. Jul 22, 2010 #1

    im trying to write my own version of the C standard function strspn.

    It returns the number of characters in str2 that exists in str1.

    I cannot get mine to work.

    Code (Text):

    #include <stdio.h>
    #include <stdlib.h>

    int strspn(const char *str1, const char *str2){

    int n;
    const char *s,*k;
    s = str1;
    k = str2;

    while(*s++ != '\0'){
       for(; *k++ != '\0';){
    if(*s == *k)
    return n;                    
    if i try it with something like strspn("1214bk","1214"), it returns 16386...
  2. jcsd
  3. Jul 22, 2010 #2
    Well, for starters you never initialize the counter n. Secondly, you need to "reset" k (i.e. make k point to str2) when s is incremented. Also, if the two strings for e.g. "asd" and "asdasd", then should strprn return 3 or 6? I.e., does it only see if the letters exist, and not how many times? In your example, it returns 6.

    It could be a good exercise to implement a method, such that it only counts the number of letters occuring in both words, and not how many times (i.e. so it returns 3, and not 6).
    Last edited: Jul 22, 2010
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook