标签:strncmp 改变 rcp ring 大小 main 字符串长度 ons put
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 }
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 }
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 }
标签:strncmp 改变 rcp ring 大小 main 字符串长度 ons put
原文地址:https://www.cnblogs.com/cuckoo-/p/10459720.html