5.1.C风格字符串的几个函数原型strlen,strcomp,strcat,strcpy,memcpy
1 #include "pch.h"
2 #include <iostream>
3 #include<cstring>
4 #include<string>
5 #include<cassert>
6 using namespace std;
7 //strlen
8 size_t str_len(const char *ptr) {
9 assert(ptr != NULL);
10 size_t cnt = 0;
11 while (*ptr++ != '\0')
12 cnt++;
13 return cnt;
14 }
15 //strcomp
16 int str_comp(const char *ptr_1, const char * ptr_2) {
17 assert(ptr_1 != NULL && ptr_2 != NULL);
18 while (*ptr_1 == *ptr_2) {
19 if (*ptr_1 == '\0')
20 return 0;
21 ++ptr_1;
22 ++ptr_2;
23 }
24 return *ptr_1 - *ptr_2;
25 }
26 //strcat
27 //切记,使用str_cat的时候一定要让第一个传进来的字符串数组有足够大的空间,否则会出错!
28 char * str_cat(char * ptr_3, const char * ptr_4) {
29 char *temp = ptr_3;
30 assert((ptr_3 != NULL) && (ptr_4 != NULL));
31 while (*ptr_3 != '\0') {
32 ptr_3++;
33 }
34 while ((*ptr_3++ = *ptr_4++) != '\0');
35
36 return temp;
37 }
38 //strcpy
39 //两个字符组数复制的时候应该具有同样的大小!
40 char * str_cpy(char * ptr_5, const char * ptr_6) {
41 assert((ptr_5 != NULL) && (ptr_6 != NULL));
42 while ((*ptr_5++ = *ptr_6++) != '\0');
43 return ptr_5;
44 }
45
46 int main() {
47 char t[4];
48 char p[50] = { 'a','b','c','\0' };
49 char p_1[] = { 'a','b','c','\0' };
50 char p_2[] = { 'a','b','c','d','\0' };
51 char p_3[] = { 'b','b','c','\0' };
52 cout << "p's length is:" << str_len(p) << endl;
53 if (str_comp(p_1, p_2) < 0)
54 cout << "p_2>p_1" << endl;
55 if (str_comp(p_1, p_3) < 0)
56 cout << "p_3>p_1" << endl;
57 if (str_comp(p, p_1) == 0)
58 cout << "p=p_1" << endl;
59 char *temp = str_cat(p,p_1);
60 while (*temp!='\0')
61 {
62 cout << *temp++;
63 }
64 cout << endl;
65 str_cpy(t, p_1);
66 for (auto x : t) {
67 cout << x;
68 }
69 }