C常用的对字符串操作的几个方法

来源:互联网 发布:淘宝卖眼镜怎么样 编辑:程序博客网 时间:2024/06/05 16:57
  1 #include <stdio.h>  2   3 int my_strlen(char s[])  4 {  5     int i = 0;  6   7     while (s[i] != '\0')  8         i++;  9  10     return i; 11 } 12  13 void my_strcpy(char dst[], char src[]) 14 { 15     int i = 0; 16  17     /* 18      *while (src[i] != '\0') 19      *{ 20      *    dst[i] = src[i]; 21      *    i++; 22      *} 23      *dst[i] = '\0'; 24      */ 25  26     while ((dst[i] = src[i]) != '\0') 27         i++; 28 } 29  30  31 void my_strcat(char dst[], char src[]) 32 { 33     int i = 0, j = 0; 34  35     while (dst[i] != '\0') 36         i++; 37  38  39     while ((dst[i++] = src[j++]) != '\0') 40         ; 41 } 42  43 int my_strchr(char s[], char ch) 44 { 45     int i = 0; 46  47     while (s[i] != '\0') 48     { 49         if (s[i] == ch) 50             return i; 51         i++; 52     } 53  54     return -1; 55 } 56  57 int my_strrchr(char s[], char ch) 58 { 59     int i = 0, r = -1; 60  61     while (s[i] != '\0') 62     { 63         if (s[i] == ch) 64             r = i; 65         i++; 66     } 67  68     return r;

 69 } 70  71 int my_strcmp(char s1[], char s2[]) 72 { 73     int i = 0; 74  75     while (s1[i] != '\0' && s2[i] != '\0' && s1[i] == s2[i]) 76         i++; 77  78     return s1[i] - s2[i]; 79 } 80  81 int my_strncmp(char s1[], char s2[], int len) 82 { 83     int i = 0; 84  85     while (--len && s1[i] != '\0' && s2[i] != '\0' && s1[i] == s2[i]) 86         i++; 87  88     return s1[i] - s2[i]; 89 } 90  91 int my_strstr(char s[], char k[]) 92 { 93     int i = 0, j = 0, y = 0, l = my_strlen(k); 94  95     while (s[i] != '\0') 96     { 97         if (k[0] == s[i]) 98         { 99             j = i;100             y = 0;101             while (--l && s[j] != '\0' && k[y] != '\0' && s[j] == k[y])102             {103                 j++;104                 y++;105             }106 107             if (s[j] == k[y])108                 return i;109         }110         i++;111     }112 }113 114 int main(void)115 {116     char a[100] = "hello";117     char b[10] = "wwlw";118     char c[100];119     char d[10] = "ow";120 121     printf("strlen = %d\n", my_strlen(a));122     my_strcpy(c, a);123     printf("strcpy = %s\n", c);124     my_strcat(c, b);125     printf("strcat = %s\n", c);126     printf("strchr = %d, strrchr = %d\n",127             my_strchr(c, 'l'), my_strrchr(c, 'l'));128 129     printf("strstr = %d\n", my_strstr(c, d));130     printf("strcmp = %d\n", my_strcmp(c, b));131 132 133     return 0;134 }

几个常用字符串操作函数

0 0
原创粉丝点击