1.strcmp
int strcmp (const char* str1, const CHAR*STR2) {
assert (str1! = null&&str2! = NULL);
while (*str1&&*str1 = = *str2) {
str1++;
str2++;
}
if (* (unsigned char*) str1 < * (unsigned char*) str2) {
return-1;
}
else if (* (unsigned char*) str1 > * (unsigned char*) str2) {
return 1;
}
else{
return 0;
}
}
Attention:
1. The parameter is const
2. Exception input processing assert (str1! = null&&str2! = NULL);
3. You must first convert the char* pointer to unsigned when comparing the size of the characters to the char*
Because the range of signed character values is -128~127, the range of unsigned character values is 0~255, and the ASCII of the string has no negative value.
For example *STR1, the value of 1,*STR2 is 255.
Originally *STR1<*STR2, but the signed number of 255 is-1. 2.strcat
Char *strcat (char* strdest, const CHAR*STRSRC) {
assert (strdest! = null&&strsrc! = NULL);
char* address = strdest;
while (*strdest! = ') ') strdest++;
while (*strsrc! = ') ' {
*strdest = *strsrc;
strdest++;
strsrc++;
}
*strdest = ' + ';//
return address;
}
1. Note the parameters and return values
2. To overwrite the original string ' + ', add ' 3.strcpy ' at the end
Char *strcpy (char* strdest, const CHAR*STRSRC) {
assert (strdest! = null&&strsrc! = NULL);
char* address = strdest;
while (*strsrc! = ') ' {
*strdest = *strsrc;
strdest++;
strsrc++;
}
*strdest = ' + ';
return address;
}
Address overlap issues should also be considered if necessary 4.memcpy
First look at the explanation of the standard memcpy ():
void * memcpy (void * destination, const void * source, size_t num);
When you implement memcpy () yourself, you need to consider the case of overlapping addresses .
#include <iostream>
#include <cstdio>
using namespace std;
void* mymemcpy (void* DST, const void* SRC, size_t n) {
if (DST = = NULL | | src = = NULL) return null;
char* PDST;
char* psrc;
if (src >= DST | | (char*) DST >= (char*) src + n-1) {
pdst = (char*) DST;
PSRC = (char*) src;
while (n--) {
*pdst++ = *psrc++;
}
}
else{
pdst = (char*) dst+ n-1;
PSRC = (char*) src+ n-1;
while (n--) {
*pdst--= *psrc--;
}
}
return DST;
}
int main () {
char buf[100] = "Abcdefghijk";
memcpy (Buf+2, buf, 5);
mymemcpy (buf + 2, buf, 5);
printf ("%s\n", buf + 2);
return 0;
}
Results
Abcdehijk