mycopy My_strlen My_strcmp My_strcat My_atoi My_itoa的實現
阿新 • • 發佈:2018-12-18
mycopy函式(4種)
void My_strcpy1(char *dest,const char *src) { int i; for( i = 0;src[i]!='\0';i++) { dest[i]=src[i]; } dest[i]='\0'; } void My_strcpy2(char *dest,const char *src) { while(*dest++=*src++); } char *My_strcpy3(char *dest,const char *src) { char *p=dest; while(*dest++=*src++); return p; } void My_strcpy4(char *dest,const char *src) { while(*src != '\0') { *dest=*src; dest++; src++; } *dest='\0'; } char *My_strcnpy(char *dest,const char *src,int n) { int i = 0; for( ; i < n && src[i] != '\0';i++) { dest[i] = src[i]; } dest[i] = '\0'; return dest; }
字串長度My_strlen
int My_strlen(const char *str)
{
int count = 0;
while(*str != '\0')
{
count++;
str++;
}
return count;
}
字串比較
int My_strcmp(const char *str1,const char *str2) { assert(str1 != NULL && str2 != NULL); int tmp = 0; while((tmp = *str1-*str2) == 0 && *str2 != '\0') { str1++; str2++; } return tmp; }
在字串尾拷貝
char *My_strcat(char *dest,const char *src) { assert(dest != NULL && src != NULL); char *p=dest; while(*dest != '\0') { dest++;//找到連線位置 } //接著複製 while(*dest++=*src++); return p; } char *My_strncat(char*dest, const char*src, int n) { assert(dest != NULL && src != NULL); char *p = dest; while (*dest != '\0') { dest++; } while (n -- != 0) { *dest++ = *src++; } *dest = '\0'; return p; }
字串變數字 My_atoi() "123" ===> 123 '1'==>1 '1' - '0' = 1 123 1*10+2 12 120+3 12*10+'3'-'0' 123
int My_atoi(const char *str)
{
assert(str != NULL);
if(str == NULL)
{
return -1;
}
while(*str == ' ')
{
str++;
}
if(*str == '-')
{
printf("-");
str++;
}
if(*str == '+')
{
str++;
}
int num = 0;
while(isdigit(*str))
{
num = num*10+*str-'0';
str++;
}
return num;
}
數字變字串My_itoa
char *My_itoa(int num,char *str)//str[] //-123 "123"
{
//123%10 = 3+'0'== '3' 12 %10 1%10 "321" "123"
//1234%10 4
//num%10+'0' num/10 = 12
//char str2[10];//出了函式的作用域 記憶體被系統回收
int i = 0;//str的下標
if(num < 0)
{
printf("-");
num = -num;
}
while(num != 0)
{
str[i] = num%10+'0';
num/=10;
i++;
}
str[i] = '\0';
i--;//從\0向前退一位
char tmp;
for(int j = 0;j < i;j++,i--)//逆置
{
tmp = str[i];
str[i] = str[j];
str[j] = tmp;
}
return str;
}