字符串操作——C语言实现
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
char ch1[]={ 'c', '+', '+'};
char ch2[]={ 'c', '+', '+', '\0'};
char ch3[] = "myC++";
char ch4[] = "good idea";
int strlen_new(const char* src);//const 2'
char* strcat_new(char *strD, const char *strS);
char* strcpy_new(char *strD, const char *strS);
int strcmp_new(const char *s1, const char *s2);
void* memcpy_new(void* dst, void* src, size_t n);
void* memmove_new(void* dst, void* src, size_t n);
void* memmove_new(void* dst, void* src, size_t n)
{
char * dp = (char*)dst;
char * sp = (char*)src;
assert(src != NULL && dst != NULL && n>0);
if(sp > dp || (sp + n) < dp)
{
while(n--)
{
*(dp++)=*(sp++);
}
*dp='\0';
}
else if (sp < dp)
{
sp += n;
dp += n;
*dp = '\0';
while(n--)
*(--dp) = *(--sp);
}
return dst;
}
void* memcpy_new(void* dst, void* src, size_t n)
{
char* dp = (char*)dst;
char* sp = (char*)src;
assert(src != NULL && dst != NULL && n>0);
while(n--)
{
*dp = *sp;
dp++;
sp++;
}
dp = '\0';
return dst;
}
int strlen_new(const char* src)
{
int count = 0;
assert(src != NULL);
while(*src++ != '\0')
{
count++;
}
return count;
}
char * strcat_new(char * strD, const char * strS)
{
char * add = strD;
assert(strD != NULL && strS != NULL);
while(*strD != '\0')
strD++;
while((*strS) != '\0')
{
*strD = *strS;
strD++;
strS++;
}
*strD = '\0';
//while(*strD++ = *strS++);//cat more efficient
return add;
}
char* strcpy_new(char *strD, const char *strS)
{
char * add = strD;
assert(strD != NULL && strS != NULL);
while(*strS != '\0')
*strD++ = *strS++;
//attention姝ゅ锛岃嫢*strS涓衡€橽0鈥橈紝鍒欏叾鍏堣祴鍊肩粰strD锛屾晠鏈€鍚庝笉闇€瑕佸啀娣诲姞'\0'
//while(*strD++ = *strS++);
*strD = '\0';
return add;
}
int strcmp_new(const char *s1, const char *s2)
{
//int ret;
assert(s1 != NULL && s2 != NULL);
while(*s1 && *s2 && *s1 == *s2)
{
s1++;
s2++;
}
return *s1 - *s2;
//return *s2 - *s1;
}
int main ()
{
int str_len = 0;
char* mem_src = "the src test memcpy";
char mem_dest[29] = "another hello";
char* mv_src = "the src test memmove";
char mv_dest[20];
printf("Test memcpy ret is :%s\n", memcpy(mem_dest, mem_src, 20));
printf("Test memmove ret is :%s\n", memmove_new(mv_dest, mv_src, 10));
str_len = strlen_new(ch3);
//printf("%s\n", strcat_new(ch3, ch4));
printf("%s\n", strcpy_new(ch3,ch4));
printf("strcmp = %d\n", strcmp_new(ch3,ch4));
printf("len = %d ,%s\n", str_len, ch3);
return 0;
}
运行结果如下:
Test memcpy ret is :the src test memcpy
Test memmove ret is :the src te
good idea
strcmp = 6
len = 5 ,good idea
Process returned 0 (0x0) execution time : 0.047 s
Press any key to continue.