Another implementation of strcmp and strncmp functions

amrith92 0 Tallied Votes 612 Views Share

My implementation of the strcmp and strncmp functions. I don't think that it is very efficient, but have managed to get both the functions' execution times to 0.01 s (At least, this is the value my profiler gives me). Enjoy! :)

/*
    Function(Fn I) compares two strings and
    returns (+1) if s1 > s2, (0) if s1 == s2,
    and (-1) if s1 < s2
    
    Note: (all comparisns are ASCII based)
*/
int aNew_strcmp(const char* s1, const char* s2)
{
    // Stores return value
    int retVal = 0;
    
    // This flag restricts the execution of the loop
    bool fFlag = true;
    
    // While s1 and s2 exist
    while(*s1++ && *s2++ && fFlag)
       (retVal != 0) ? fFlag = false : (*s1 > *s2) ? ++retVal : (*s1 < *s2) ? --retVal : retVal = retVal;
       /* What the above statement does:
               
          Condition 1:
                    
            retVal, if it has been modified to a value not equal to 0, then terminate the loop
            by setting the flag to be false. This will restrict the value retVal to 0, 1, or -1.
                       
          Condition 2:
                    
            If the (Condition 1) fails, then it checks whether the current character pointed by
            s1 is > the current character pointed by s2. If true, then increment value of retVal.
                       
          Condition 3:
            If (Condition 1) and (Condition 2) both fail, then decrement the value of retVal.
            If this condition fails as well, then leave retVal alone (as *s1 == *s2).
       */
    
    // Return retVal, which can be 0, 1, or -1
    return retVal;
}

/*
    Function(Fn II) compares two strings until
    (s1 or s2) terminates or uptil 'num' number of characters, &
    returns (+1) if s1 > s2, (0) if s1 == s2,
    and (-1) if s1 < s2
    
    Note: (all comparisns are ASCII based)
*/
int aNew_strncmp(const char* s1, const char* s2, int num)
{
    // Stores return value
    int retVal = 0;
    
    // This flag restricts the execution of the loop
    bool fFlag = true;
    
    while(*s1++ && *s2++ && --num > 0 && fFlag)
       (retVal != 0) ? fFlag = false : (*s1 > *s2) ? ++retVal: (*s1 < *s2) ? --retVal : retVal = retVal;
       // refer to the function above
    
    // Return retVal, which can be 0, 1, or -1
    return retVal;
}
mvmalderen 2,072 Postaholic

strcmp can also be written like this :D:

int strcmp(const char *s1, const char *s2) {
    while( ( *s1 && *s2 ) && ( *s1++ == *s2++ ) );
    return *( --s1 ) - *( --s2 );
}

However, I didn't include code to avoid a NULL-pointer in my code, but it might be wise to do so as well :)

amrith92 119 Junior Poster

Wow! Good code :) beats mine by a mile... :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.