模拟实现strncpy,strncat,strncmp

1.模拟实现strncpy 
<1.>strncpy相比于strcpy增加了size_t参数可以实现最多拷贝的字节数
<2.>(size_t不可以超出拷贝存放的内存大小)来保证不会超出destanaton的内存,
<3.>但是需要注意的是,如果你需要拷贝的长度小于源字符串长度,那么strncpy不会在末尾加'\0'
 1 #include<stdio.h>
 2 #include<assert.h>
 3 #include<string.h>
 4 char* Strncpy(char* destination, const char* source, size_t num)
 5 {
 6  size_t i = 0;
 7  while (i<num)
 8  {
 9   destination[i] = source[i];
10   ++i;
11  }
12  return destination;
13 }
14 int main()
15 {
16  char str1[] = "To be or not to be";
17  char str2[40];
18  char str3[40];
19  //拷贝最大的字节
20  Strncpy(str2, str1, sizeof(str2));
21  //拷贝小于str1的字节
22  Strncpy(str3, str2, 5);
23  str3[5] = '\0'; //需要自己加如'\0' 
24  puts(str1);
25  puts(str2);
26  puts(str3);
27  return 0;
28 }

 

  2.模拟实现strncat
<1.>现在destination函数中找到'\0',然后将source函数中的num个字符拼接到destination中
<2.>注意source函数不能修改,需要加const
<3.>返回结果是指针类型
 1 #include<stdio.h>
 2 #include<assert.h>
 3 char* Strncat(char* destination, const char* source, size_t num)
 4 {
 5  //检查合法性
 6  assert(destination != NULL);
 7  assert(source != NULL);
 8  //找到destination中的'\0'
 9  int i = 0;
10  while (destination[i]!='\0')
11  {
12   i++;
13  }
14  //拼接字符串
15  for (int j = 0; num > 0; i++, j++, num--)
16  {
17   destination[i] = source[j];
18  }
19  destination[i] = '\0';
20  return destination;
21 }
22 int main()
23 {
24  char str1[40] = "abcd";
25  char str2[] = "efghijklmn";
26  //拼接前4个字符
27  Strncat(str1,str2,4);
28  puts(str1);
29  printf("\n");
30  //拼接全部字符,(因为上一个Strncat已经改变了str1的值)
31  Strncat(str1, str2, sizeof(str2));
32  puts(str1);
33  return 0;
34 }

 

  3.模拟实现strncmp
<1.>strncmp返回值与strcmp一样
<2.>如果str1与str2前num个字符一样则返回0
<3.>str1小于str2则返回一个小于0的数
<4.>str1大于str2则返回一个大于0的数
 1 #include <stdio.h>
 2 #include<assert.h>
 3 #include<string.h>
 4 int Strncmp(const char* str1, const char* str2, size_t num)
 5 {
 6  assert(str1 != NULL);
 7  assert(str2 != NULL);
 8  while (num>0)
 9  {
10   if (*str1 > *str2)
11   {
12    return 1;
13   }
14   else if (*str1 < *str2)
15   {
16    return -1;
17   }
18   else if (*str1 == *str2)
19   {
20    str1++;
21    str2++;
22    num--;
23   }
24   else
25   {
26    str1++;
27    str2++;
28    num--;
29   }
30  }
31  return 0;
32 }
33 int main()
34 {
35  char str1[] = "abcdef";
36  char str2[] = "abty";
37  //模拟实现Strncmp
38  printf("%d\n", Strncmp(str1, str2, 2));//前两个字符相等
39  printf("%d\n", Strncmp(str1, str2, 3));//前三个字符不相等
40  printf("%d\n", Strncmp("abcde", "abc", 4));//str1大于str2
41  printf("%d\n", Strncmp("abc", "abcde", 4));//str1小于str2
42  printf("\n");
43  //库函数strncmp
44  printf("%d\n", strncmp(str1, str2, 2));
45  printf("%d\n", strncmp(str1, str2, 3));
46  printf("%d\n", strncmp("abcde", "abc", 4));
47  printf("%d\n", strncmp("abc", "abcde", 4));
48  return 0;
49 }

 

上一篇:CF786B Legacy 线段树优化建图


下一篇:CF786B Legacy(线段树优化建图+最短路)