C语言——模拟实现库函数(strcat,strcmp,strcpy,srelen)

40 篇文章 3 订阅

分别模拟实现库函数
1.strcat
2.strcmp
3.strcpy
4.srelen

1.strcat

#include<stdio.h>
#include<string.h>

void Merge(char a[], char b[], int n)
{
    char* q = a;
    char* p = b;
    int m = 0;
    while (*q != '\0')
        q++;
    while (m <= n) {
        *q++ = *p++;
        m++;
    }
    puts(a);
}

int main()
{
    char a[100] = { 0 };
    char b[100] = { 0 };
    gets(a);
    gets(b);
    int n = strlen(b);
    Merge(a, b, n);
}

2.strcmp

#include <stdio.h>
#include <assert.h>

int Strcmp(const char* str1, const char* str2) {
    assert(str1 != NULL);
    assert(str2 != NULL);
    while (*str1 == *str2) {
        if (*str1 == '\0') {
            return 0;
        }
        ++str1;
        ++str2;
    }
    return *str1 - *str2;
}
int main() {
    char str1[] = "love";
    char str2[] = "move";
    int point = Strcmp(str1, str2);
    if (point == 0) {
        printf("str1 = str2\n");
    }
    else if (point > 0) {
        printf("str1 > str2\n");
    }
    else {
        printf("str1 < str2\n");
    }
    return 0;
}

3.strcpy

#include<stdio.h>
#include<string.h>

void my_strcpy(char *arr_1, char *arr_2)
{
    while (*arr_2!=0) {
        *arr_1++ = *arr_2++;
    }
}

int main()
{
    char arr_1[100] = { 0 };
    char arr_2[100] = { 0 };
    gets_s(arr_1);
    /*int a = strlen(arr_1);*/
    gets_s(arr_2);
    my_strcpy(arr_1, arr_2);
    printf("%s", arr_1);
}

4.srelen

#include<stdio.h>

void my_strlen(char* arr)
{
    int count = 0;
    while (*arr != 0) {
        arr++;
        count++;
    }
    printf("%d", count);
}

int main()
{
    char arr[100] = { 0 };
    gets_s(arr);
    my_strlen(arr);
}
  • 7
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值