字符串的模拟

1.模拟实现strncpy

将一个字符串的n和字符复制到字符数组.

#define _CRT_SECURE_NO_WARNINGS 0
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<assert.h>
char My_strncpy(char arr[], char brr[], int length)
{ 
    assert(brr);
    assert(arr);
    int m = strlen(brr);    
    int i;
    if (m>=length)
    {
      for ( i = 0; i < length; i++)
        {
          arr[i] = brr[i];
         }
       arr[length] = '\0';

    }
    else
    {
        printf("Enter again!!\n");
        system("pause");
        exit(1);
    }
}
int main()
{
    char arr[100];
    char brr[100];
    int length;
    printf("please input arr:");
    gets(arr);
    //fflush(stdin);
    printf("Please enter the to be copied:");
    scanf("%d", &length);
    My_strncpy(brr, arr, length);
    printf("%s\n", brr);
    //puts(brr);
    system("pause");
    return 0;
}

2.模拟实现strncat

将一个字符串的前n个字符添加在另一个字符串中.

#define _CRT_SECURE_NO_WARNINGS 0
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
char My_strncat(char *arr, const char *brr, const int length)
{
    assert(arr);
    assert(brr);
    int i = 0;
    while (*arr)
    {
        arr++;
    }
    for ( i =  0; i < length; i++)
    {
        arr[i] = brr[i];
    }
    arr[length] = '\0';
}
int main()
{
    char arr[100];
    char brr[100];
    int length;
    printf("Please enter arr:");
    gets(arr);
    printf("Please enter brr:");
    gets(brr);
    printf("Please input length:");
    scanf("%d", &length);
    My_strncat(arr, brr, length);
    puts(arr);
    system("pause");
    return 0;
}

3.模拟实现strncmp

两个字符串的比较,如果两个字符串相等strncmp将返回0

#define _CRT_SECURE_NO_WARNINGS 0
#include<stdio.h>  
#include<stdlib.h>
#include<string.h>  
#include<assert.h>  
int my_strncmp(const char*arr1, const char*arr2, size_t length)
{
    assert(arr1);
    assert(arr2);
    while (length--)
    {
        while (*arr1 == *arr2)
        {
            if (*arr1 == '\0')
                return 0;
            else if (*arr2 == '\0')
                return 0;
            arr1++;
            arr2++;
        }
        return*arr1 - *arr2;
    }
}
int main()
{
    char arr1[100];
    char arr2[100];
    int length;
    printf("Please input arr1:");
    gets(arr1);
    printf("Please input arr2:");
    gets(arr2); 
    printf("Please input length:");
    scanf("%d", &length);
    int ret = my_strncmp(arr1, arr2, length);
    if (ret == 0)
    {
        printf("arr1=arr2");
    }
    else if(ret>0)
    {
        printf("arr1>arr2");
    }
    else
    {
        printf("arr1<arr2");
    }
    system("pause");
    return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lao_wine

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值