1.memmove
void *memmove(void *dest,const void *src,size_t count)
memmove用于从source拷贝count个字符到dest,
如果目标区域和源区域有重叠的话,memmove能够保证在源串覆盖之前将重叠区域的字节拷贝到目标区域中
void *memmove(void *dest,const void *src,size_t count)
{
assert((NULL != dest) && (NULL != src));
char *tmp_dest = (char *)dest;
char *tmp_src = (char *)src;
if(tmp_dest + count < tmp_src || tmp_src + count < tmp_dest)//没有重叠区域
{
while(count--)
{
*tmp_dest++ = *tmp_src++;
}
}
else
{
//从后往前移动数据,保证数据正确复制
tmp_dest = tmp_dest + count - 1;
tmp_src = tmp_src + count - 1;
while(count--)
{
*tmp_dest-- = *tmp_src--;
}
}
return dest;
}
2.memcpy不考虑内存重叠
void *memcpy(void *dest,const void *src,size_t count)
{
assert((NULL != dest) && (NULL != src));
char *tmp_dest = (char *)dest;
char *tmp_src = (char *)src;
while(count--)
{
*tmp_dest++ = *tmp_src++;
}
return dest;
}
3.strcpy实现
char *strcpy(char *dest,const char *src)
{
assert((NULL != dest) && (NULL != src));
char *tmp_dest = dest;
while((*tmp_dest++ = *src++) != '\0')
{
;
}
return dest;
}
4、strcmp实现
int my_strcmp(const char *dest,const char *src)
{
assert((NULL != dest) && (NULL != src));
while(*dest && *src && (*dest == *src))
{
dest++;src++;
}
//字符不相等
//dest > src 返回值大于0
//dest == src 返回值等于0
//dest < src 返回值小于0
if(*dest == *src)
return 0;
if(*dest > *src)
return 1;
else
return -1;
}
5、strncmp
int my_strncmp(const char *dest,const char* src,int len)
{
assert(NULL != dest && src != NULL);
while(*dest && *src && (*dest == *src)&&len--)
{
dest++;src++;
}
if(len == 0)
{
return 0;
}
if(*dest > *src)
{
return 1;
}
else
5、二分查找
int BinaryFind(int *arr,int n,int val)
{
int left = 0;
int right = n-1;
while(left <= right)
{
int mid = (right - left)/2 + left;
if(arr[mid] == val)
{
//return mid;
while(arr[mid] == val)//返回第一个该数字下标
{
mid--;
}
return mid+1;
}
if(arr[mid] > val)
{
right = mid-1;
}
else
{
left = mid + 1;
}
}
return -1;
}
6、16进制转换10进制
int HexToDec(char *s)
{
if(NULL == s) return 0;
int len = strlen(s);
int res = 0;
for(int i=0;i<len;i++)
{
if(s[i] >= '0' && s[i] <= '9')
{
res = res * 16 + s[i] - '0';
}
if(s[i] >= 'a' && s[i] <= 'f')
{
res = res * 16 + s[i] - 'a' + 10;
}
}
return res;
}
int main()
{
char *s = "aab";
cout<<HexToDec(s)<<endl;
return 0;
}