实现C语言字符串操作的库函数

来源:互联网 发布:sai软件上色教程 编辑:程序博客网 时间:2024/05/13 10:36
[cpp] view plaincopyprint?
  1. #include <stdio.h>  
  2.   
  3. //求字符串串长(版本一)  
  4. //用字符数组实现  
  5. int mystrlen1(char s[])  
  6. {  
  7.     int len = 0;  
  8.     while(s[len] != '\0')  
  9.     {  
  10.         len++;  
  11.     }  
  12.       
  13.     return len;  
  14. }   
  15.   
  16. //求字符串串长(版本二)  
  17. //用字符指针实现   
  18. int mystrlen2(char *s)  
  19. {  
  20.     int len = 0;  
  21.       
  22.     while (*s != '\0')  
  23.     {  
  24.         len++;  
  25.         s++;  
  26.     }  
  27.       
  28.     return len;  
  29. }  
  30.   
  31. int main()  
  32. {  
  33.     char str[] = "hello";  
  34.     int n = mystrlen1(str);  
  35.     printf("%d\n",n);  
  36.       
  37.     int m = mystrlen2(str);  
  38.     printf("%d\n",m);  
  39.     return 0;  
  40. }  
[cpp] view plaincopyprint?
  1. #include <stdio.h >  
  2.   
  3. //字符串拷贝(版本一)  
  4. //用数组实现   
  5. void mystrcpy1(char s[],char t[])  
  6. {  
  7.     int i=0;  
  8.     while((s[i]=t[i]) != '\0'//先赋值,再比较是否为串结束符  
  9.     {  
  10.         i++;  
  11.     }  
  12. }   
  13.   
  14. //字符串拷贝(版本二)  
  15. //用指针实现  
  16. void mystrcpy2(char *s,char *t)  
  17. {  
  18.     while((*s = *t) != '\0')  
  19.     {  
  20.         s++;  
  21.         t++;  
  22.     }  
  23. }  
  24.   
  25. //字符串拷贝(版本三)  
  26. //用指针实现  
  27. void mystrcpy(char *s, char *t)  
  28. {  
  29.     while (*s++ = *t++);   //C中非0即表示逻辑真,所以不用和’\0’比较了  
  30.               
  31. }  
  32.    
  33. int main()  
  34. {  
  35.     char a[] ="hello";  
  36.     char b[100],c[100];  
  37.     mystrcpy1(b,a);  
  38.     printf("%s\n",b);  
  39.       
  40.     mystrcpy2(c,a);  
  41.     printf("%s\n",c);  
  42.     return 0;  
  43. }  

[cpp] view plaincopyprint?
  1. #include <stdio.h>  
  2.   
  3. //字符串比较版本一  
  4. //用数组实现   
  5. int mystrcmp1(char s[],char t[])  
  6. {  
  7.     int i;  
  8.     for(i=0;s[i]==t[i];i++)  
  9.     {  
  10.         if(s[i]=='\0')  
  11.         {  
  12.             return 0;  
  13.         }  
  14.     }  
  15.     return s[i]-t[i];  
  16. }  
  17.   
  18. //字符串比较版本二  
  19. //用字符指针实现  
  20. int mystrcmp2(char *s,char *t)  
  21. {  
  22.     while(*s == *t)  
  23.     {  
  24.         if(*s == *t)  
  25.         {  
  26.             return 0;  
  27.         }  
  28.         s++;  
  29.         t++;  
  30.     }  
  31.     return *s-*t;  
  32. }   
  33. int main()  
  34. {  
  35.     char s1[] = "hello",s2[] = "Java";  
  36.     printf("%d\n",mystrcmp1(s1,s2)>0?1:-1);  
  37.     printf("%d\n",mystrcmp2(s1,s2)>0?1:-1);  
  38.     return 0;  
  39. }   
0 0