-
C++ (
http://www.daniweb.com/forums/forum8.html)
| amrith92 | May 25th, 2009 7:25 pm | |
| Another implementation of strcmp and strncmp functions 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;
}
| tux4life | May 28th, 2009 2:16 am | |
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 | May 28th, 2009 2:22 pm | |
| Wow! Good code :) beats mine by a mile... :) |
| All times are GMT -4. The time now is 7:58 pm. | |
Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC