The following describes how to use strcat and strcpy, common string functions in C language. For more information, see
Strcpy prototype Declaration: extern char * strcpy (char * dest, const char * src );
Header file :#Include <string. h>
Function:Copy the string starting with the src address and containing the NULL terminator to the address space starting with dest.
Note:The memory areas specified by src and dest cannot overlap and dest must have enough space to hold src strings.
Returns the pointer to dest.
Function implementation:
Copy codeThe Code is as follows:
/**********************
* A typical industrial implementation of the C standard library function strcpy
* Return value: the address of the target string.
* The ANSI-C99 standard is undefined in case of an exception, so the real determines the return value, usually NULL.
* Parameters:
* StrDestination target string
* StrSource source string
***********************/
Char * strcpy (char * strDestination, const char * strSource)
{
Assert (strDestination! = NULL & strSource! = NULL );
Char * strD = strDestination;
While (* strD ++ = * strSource ++ )! = '');
Return strDestination;
}
/*
Implementation in GNU-C (excerpt ):
*/
Char * strcpy (char * d, const char * s)
{
Char * r = d;
While (* d ++ = * s ++ ));
Return r;
}
/* While (* d ++ = * s ++); the two-layer brackets are used to obtain the value of the value assignment expression,
The value of the value assignment expression is the left operand, so the loop stops after NULL is copied */
Strcat prototype
Extern char * strcat (char * dest, char * src );
Usage
# Include <string. h>
In C ++, it is stored in the <cstring> header file.
Function
Add the string indicated by src to the end of dest (overwrite ''at the end of dest) and add ''.
Description
The memory areas specified by src and dest cannot overlap and dest must have enough space to hold src strings.
Returns the pointer to dest.
Function implementation:
Copy codeThe Code is as follows:
// Add the source string to const, indicating that it is an input parameter
Char * strcat (char * strDest, const char * strSrc)
{
// Return address, so the address cannot be declared after assert assertions.
Char * address = strDest;
Assert (strDest! = NULL) & (strSrc! = NULL); // Add non-0 assertions to the source and target addresses
While (* strDest) // is while (* strDest! = '').
{
// If you use while (* strDest ++), an error occurs, because after the loop ends, strDest executes ++ again,
// StrDest points to the next location. /So it must be in the body of the loop ++; because if * strDest refers
// End flag to the string ''.
StrDest ++;
}
While (* strDest ++ = * strSrc ++)
{
NULL; // you can use ++ in this loop condition,
} // The statement * strDest = ''can be added here; no need
Return address; // return the destination address for chained operations
}