Self-implemented library functions 1 (strlen, strcpy, strcmp, strcat), strcmpstrcat
To facilitate understanding and use of library functions, first present the following functions and test functions.
// Evaluate the string length Function
Int my_strlen (const char * pStr)
{
Assert (pStr! = NULL );
Int length = 0;
While (* pStr ++! = '\ 0 ')
{
Length ++;
}
Return length;
}
// String copy Function
Char * my_strcpy (char * strDest, const char * strSrc)
{
Assert (strDest! = NULL & strSrc! = NULL );
Char * pDest = strDest; // protection Parameter
Const char * pSrc = strSrc;
While (* pSrc! = '\ 0 ')
{
* PDest ++ = * pSrc ++;
}
// * PDest = '\ 0'; // The Library Function strcpy does not copy' \ 0'
Return strDest;
}
// String comparison Function
Int my_strcmp (const char * strDest, const char * strSrc)
{
Assert (strDest! = NULL & strSrc! = NULL );
If (* strDest = '\ 0' & * strSrc! = '\ 0 ')
{
Return 0;
}
Const char * pDest = strDest;
Const char * pSrc = strSrc;
Int result = 0; // used to record the comparison result
While (* pDest! = '\ 0' | * pSrc! = '\ 0 ')
{
If (result = * pDest-* pSrc )! = 0)
{
Break; // jumps out when the two strings are not equal.
}
PDest ++;
PSrc ++;
}
If (result> 0)
{
Result = 1;
}
Else if (result <0)
{
Result =-1;
}
Return result;
}
// String concatenation Function
Char * my_strcat (char * strDest, char * strSrc)
{
Assert (strDest! = NULL & strSrc! = NULL );
Char * pDest = strDest;
Char * pSrc = strSrc;
While (* pDest! = '\ 0') // first point pDest to the end of the string
{
PDest ++;
}
While (* pSrc! = '\ 0 ')
{
* PDest ++ = * pSrc ++;
}
* PDest = '\ 0 ';
Return strDest;
}
void Test()
{
char c1[5] = "abcd";
char c2[4] = "123";
char c3[20] = "123456";
Printf ("c1-length: % d \ n", my_strlen (c1 ));
Printf ("my_strcpy (c1, c2): % s \ n", my_strcpy (c1, c2 ));
// Printf ("% s \ n", my_strcpy (c1, c3); // the program will crash if it cannot process this out of range !!
Printf ("my_strcmp (c1, c2): % d \ n", my_strcmp (c1, c2 ));
Printf ("my_strcmp (c2, c3): % d \ n", my_strcmp (c2, c3 ));
Printf ("my_strcat (c3, c2): % s \ n", my_strcat (c3, c2 ));
}