To do a problem with the sprintf to write a character array (string) into a two-dimensional character array, and then take a long time, think of strcpy seems to be able to, it turns out that strcpy efficiency is even higher, and then think of the memcpy seems to be able to think. Practice a bit really can, efficiency needless to say also higher than sprintf, after all, memcpy is the memory operation. Then I will Baidu a bit of their differences, make a summary (note).
- sprintf can use%s to implement formatted writes, and the other two cannot.
- The strcpy encounters the end of the (also copied) and can only copy strings.
- memcpy is copied according to size, and can replicate various data types (struct, array).
For the copy string, we select strcpy, because memcpy also needs to supply the size parameter, and strcpy another advantage is that the return value is char *, which is the first address of the target string, so that the chained expression can be written:
Strlen (strcpy (s1,strcpy (DEST,SRC)));
The realization of strcpy
char * strcpy (char * strDest, const char * strSrc); // copy strSrc to strDest
{
If ((strSrc == NULL) || (strDest == NULL)) // Judging parameter validity
{
Return NULL;
}
Char * dest = strDest; // Save the first address of the target string
While ((* strDest ++ = * strSrc ++)! = ‘\ 0’); // Copy the contents of the src string to dest
Return dest;
}
The realization of memcpy
void * memcpy (void * memTo, const void * memFrom, size_t size)
{
If ((memTo == NULL) || (memFrom == NULL)) // memTo and memFrom must be valid
return NULL;
Char * tempFrom = (char *) memFrom; // Save the first address of memFrom
Char * tempTo = (char *) memTo; // Save memTo first address
While (size-> 0) // loop size times, copy the value of memFrom to memTo
* TempTo ++ = * tempFrom ++;
Return memTo;
}
Related: string.h character functions commonly used in C language
The difference between sprintf, strcpy and memcpy