在现在的Linux版本下,支持许多的API函数,平时我们用得是挺舒服的,但是我们不光要用API函数,更重要的是,我们要知道这些API函数是怎样工作,执行的。我就用字符串的几个重要的函数来举例
一:字符串比较函数strcmp();
#include <stdio.h>
#define MAX_SIZE 1024
int my_strcmp(charchar *dest, charchar *src)
{
charchar *temp = dest;
while(*src != '\0')
{
if(*temp > *src)
{
return 1;
}
else if(*temp < *src)
{
return -1;
}
temp++;
src++;
}
if(*src == '\0' && *temp == '\0')
{
return 0;
}
if(*src == '\0' && *temp != '\0')
{
return 1;
}
if(*temp == '\0' && *src != '\0')
{
return -1;
}
}
int main()
{
char src[MAX_SIZE] = "hello world a";
char dest[MAX_SIZE] = "hello world ";
int result = my_strcmp(dest,src);
printf("result = %d\n",result);
return 0;
}
二:字符串连接函数strcat();
#include <stdio.h>
#define MAX_SIZE 1024
charchar *my_strcat(charchar *dest, charchar *src)
{
charchar *temp = dest;
while( *temp != '\0')
{
*temp++;
}
while(*src != '\0')
{
*temp = *src;
*temp++;
*src++;
}
*temp = '\0';
return dest;
}
int main()
{
char src[MAX_SIZE] = "hi where are yo doing";
char dest[MAX_SIZE] = "how are you";
charchar *temp = my_strcat(dest,src);
printf("temp = %s\n",temp);
printf("dest = %s\n",dest);
return 0;
}
三:字符串长度strlen();
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 1024
int my_strlen(charchar * src)
{
int len = 0;
while( * src != '\0')
{
*src++;
len++;
}
return len;
}
int main()
{
char src[MAX_SIZE] = "hello world";
int len;
len = my_strlen(src);
printf("the len = %d\n",len);
return 0;
}
四:字符串拷贝函数strcpy();
#include <stdio.h>
#include <string.h>
#define MAX_SIZE
charchar *my_strcpy(charchar *dest, charchar *src)
{
charchar *temp = dest;
while(*src != '\0')
{
*temp = *src;
*temp++;
*src++;
}
*temp = '\0';
return dest;
}
int main()
{
char src[MAX_SIZE] = "welcome to china";
char dest[MAX_SIZE] = "hello world";
charchar *temp = my_strcpy(dest,src);
printf("temp = %s\n",temp);
printf("dest = %s\n",dest);
return 0;
}