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

  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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值