C语言基础(二)

来源:互联网 发布:vi保存退出ubuntu 编辑:程序博客网 时间:2024/05/16 08:48

编程实现mystrcat函数

#include<stdio.h>#include<stdlib.h>char *mystrcat(char *str, const char *ptr){    char *result;    result = str;    while(*str++);    str--;    while(*str++ = *ptr++);    return result;}int main(void){    char *a = NULL;    char *b = "hello ";    char *c = "world";    a = (char *)malloc(256);    *a = '\0';    mystrcat(mystrcat(a, b), c);    printf("a: %s\n",a);    free(a);    a = NULL;    return 0;}

编程实现mystrcmp函数

#include<stdio.h>#include<string.h>int mystrcmp(const char *str, const char *ptr){    int result = 0;    while( !(result = *(unsigned char *)str - *(unsigned char *)ptr) && *ptr)    {        ++str;        ++ptr;    }    if ( result < 0 )        result = -1;    else if ( result > 0 )        result = 1;    return (result);}int main(){    char a[10] = "1234567";    char b[10] = "1234567";    char c[10] = "12345678";    char d[10] = "1234566";    int test1 = mystrcmp(a, b);    int test2 = mystrcmp(a, c);    int test3 = mystrcmp(a, d);    printf("test1 = %d\n",test1);    printf("test2 = %d\n",test2);    printf("test3 = %d\n",test3);    return 0;}

编程实现mystrcopy函数

#include<stdio.h>char *strcpy(char *str, const char *ptr){    if((str == NULL) || (ptr == NULL))    {        return NULL;    }    char *strcopy = str;    while ((*str++ = *ptr++) != '\0');    return strcopy;}int getstrlen(const char *ptr){    int len = 0;    while(*ptr++ != '\0')    {        len++;    }    return len;}int main(){    char a[] = "hello world!";    char b[20];    int len = 0;    len = getstrlen(strcpy(b,a));    printf("b: %s\n",b);    printf("Length of b: %d",len);    return 0;}
原创粉丝点击