1strcmp and strncmp
1 #include <stdio.h>
2 #include <string.h>
3 /*
4 strcmp and strncmp 自实现
5 */
6 int mystrcmp(const char *str,const char *str1)
7 {
8 for(;*str&&*str1&&*str == *str1;str++,str1++);
9 return *str - *str1;
10 }
11 int mystrncmp(const char *strn,const char *strn1,int n)//2个字符串前n个字符作为子串,然后比较这2个子串的大小
12 {
13 for(;*strn&&*strn1&&*strn == *strn1&& --n;strn++,strn1++);
14 return *strn - *strn1;
15 }
16 int main(void)
17 {
18 //strcmp自实现
19 char *str = "12345688";
20 char *str1 = "1234567";
21 int val = mystrcmp(str,str1);
22 if(0 == val)
23 printf("str == str1
");
24 else if(val > 0)
25 printf("str>str1
");
26 else
27 printf("str<str1
");
28 //strncmp自实现
29 char *strn = "131";
30 char *strn1 = "121";
31 int val1 = mystrncmp(strn,strn1,3);
32 if(0 == val1)
33 printf("str == str1
");
34 else if(val1 > 0)
35 printf("str>str1
");
36 else
37 printf("str<str1
");
38
39 return 0;
40 }
2.strcpy and strncpy 自实现精炼版本
1 #include <stdio.h>
2 #include <string.h>
3 /*
4 strcpy and strncpy 自实现
5 */
6 char * mystrcpy(char *str,const char *str1)
7 {
8 char *p = str;
9 while(*str++ = *str1++);
10
11 return p;
12 }
13 char *mystrncpy(char *strn,const char *strn1,int n)
14 {
15 char *pp = strn;
16 while(n--)
17 {
18 *strn++ = *strn1++;
19 }
20 return pp;
21 }
22 int main(void)
23 {
24 //strcpy自实现
25 char str[10];
26 char *str1 = "123456";
27 char * p =mystrcpy(str,str1);
28 printf("%s
",str);
29
30 //strncpy自实现
31 char strn[10];
32 char *strn1 = "123456";
33 char *pp = mystrncpy(strn,strn1,10);
34
35 printf("%s
",strn);
36
37 return 0;
38 }
3.strcat and strncat 自实现精炼版本
1 #include <stdio.h>
2 #include <string.h>
3 /*
4 strcat and strncat 自实现
5 */
6 char * mystrcat(char *str,const char *str1)
7 {
8 char *p = str;
9 while(*str)str++;
10 while(*str++ = *str1++);
11 return p;
12 }
13 char *mystrncat(char *strn,const char *strn1,int n)
14 {
15 char *p = strn;
16 while(*strn)strn++;
17 while(n--)
18 *strn++ = *strn1++;
19 return p;
20 }
21 int main(void)
22 {
23 //strcat 自实现
24 char str[20] = "12345";
25 char *str1 = "678910";
26 char *p = mystrcat(str,str1);
27 printf("%s
",str);
28 //strncat自实现
29 char strn[20] = "12345";
30 char *strn1 = "678910";
31 char *pp = mystrncat(strn,strn1,4);
32 printf("%s
",strn);
33
34 return 0;
35 }