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;
}