今天复习之指针即使用指针进行的函数传参,优化一下昨天写的strcpy strcmp strlen strcat,添加了strstr、atoi函数,算是熟悉之前的知识汇总,顺便练习一下封装函数和书写函数的逻辑思维。
只贴上函数实现,头文件声明和调用和昨天几乎一致
#include <stdio.h>
int lenth(char *src)
{
int i =0;
if(src == NULL)
return i;
while(src[i] != '\0')
i++;
return i;
}
char * cpy(char *dest,char *src){
if(dest == NULL || src == NULL){
printf("input error");
return NULL;
}
int i = 0;
while(*(src+i) = '\0'){
*(dest+i) = *(src+i);
i++;
}
*(dest+i) = '\0';
return dest;
}
char * cat(char *dest,char *src){
if(dest == NULL || src == NULL){
printf("input error\n");
return NULL;
}
int i = 0,j = 0;
int k;
while(*(src+i) != '\0')
i++;
while(*(dest+j) != '\0')
j++;
for(k=0;k<i;k++)
*(dest+j+k) = *(src+k);
*(dest+j+k) = '\0';
return dest;
}
int compare(char *dest,char *src){
if(dest == NULL || src == NULL){
printf("input error\n");
return 999;
}
int i;
for(i = 0;;i++){
if(src[i] > dest[i])
return -1;
else if(src[i] < dest[i])
return 1;
else{
if(src[i] == '\0' && dest[i]=='\0') break;
else continue;
}
return 0;
}
}
char * strstr(char *src,char *sub){
char *s = sub;
char *h ;
if(src == NULL || sub == NULL){
printf("input error\n");
return NULL;
}
while(*src){
h = src;
sub = s;
while(*src == *sub){
src++;
sub++;
if(*sub=='\0')return h;
}
src = h;
src++;
}
return NULL;
}
int atoi(char *src){
if(src == NULL){
printf("src input error!\n");
return 0;
}
long ret=0;
int symble,i=0;
char *p =src;
while(*p != '\0'){
if(*p>'9'|| (*p<'0' && *src != '+' && *src !='-'))
{
printf("str can not change\n");
return 0;
}
p++;
}
p=src;
if(*src == '-'){
symble = -1;
p=src+1;
}
else if(*src == '+'){
symble = 1;
p =src+1;
}
else{
symble = 1;
p=src;
}
while(*p != '\0'){
if(i=0)
ret = *p-48;
else
ret = ret * 10 + (*p - 48);
i++;
p++;
}
return ret*symble;
}