C语言

来源:互联网 发布:路小雨知乎 编辑:程序博客网 时间:2024/05/29 02:02
  1. 1.strlen()函数的实现(求字符串长度的函数)  
  2.   
  3. #include <stdio.h>  
  4. #include <assert.h>  
  5.   
  6. int my_strlen(const char *str)  
  7. {  
  8.   int count=0;  
  9.   assert(str!=NULL);  
  10.   while(*str)  
  11.   {  
  12.     count++;  
  13.                 str++;  
  14.   }  
  15.   return count;  
  16. }  
  17. int main()  
  18. {  
  19.   char *string= "abcdef  ds123";  
  20.   printf("%d\n",my_strlen(string));  
  21.   system("pause");  
  22.   return 0;  
  23. }  
  24.   
  25. 2.strcmp()函数的实现(比较字符串的函数)  
  26.   
  27. #include <stdio.h>  
  28. #include <assert.h>  
  29.   
  30. int my_strcmp(const char *str1, const char *str2)  
  31. {  
  32.   assert(str1!=NULL);  
  33.   assert(str2!=NULL);  
  34.   while(*str1 && *str2  && (*str1==*str2))  
  35.   {  
  36.     str1++;  
  37.                 str2++;  
  38.   }  
  39.   return *str1-*str2;  
  40. }  
  41. int main()  
  42. {  
  43.   char *str1= "abcdde";  
  44.   char *str2= "abcdef";  
  45.   printf("%d\n",my_strcmp(str1,str2));  
  46.   system("pause");  
  47.   return 0;  
  48. }  
  49.   
  50. 3.strcpy()函数的实现(将一个字符串复制到另一个数组中,并将其覆盖)  
  51.   
  52. #include <stdio.h>  
  53. #include <assert.h>  
  54.   
  55. char *my_strcpy(char *dest,const char *scr)    //*scr将*dest里的东西覆盖  
  56. {  
  57.   char *ret=dest;  
  58.   assert(dest!=NULL);  
  59.   assert(scr!=NULL);  
  60.   while(*scr)  
  61.   {  
  62.     *dest=*scr;  
  63.                 scr++;  
  64.                 dest++;  
  65.   }  
  66.   *dest='\0';  
  67.   return ret;  
  68. }  
  69. int main()  
  70. {  
  71.                  char str1[100]="I love the world" ;   //注意此处str1必须是个数组,因为如果是个常量字符串,它就不能被改变了  
  72.                  char *str2="China" ;  
  73.                 printf( "%s\n",my_strcpy(str1,str2));  
  74.   system("pause");  
  75.   return 0;  
  76. }  
  77.   
  78. 4.strcat()函数的实现(字符串连接函数)  
  79.   
  80. #include <stdio.h>  
  81. #include <assert.h>  
  82.   
  83. char *my_strcat(char *dest,const char *scr)  
  84. {  
  85.   char *ret=dest;  
  86.   assert(dest!=NULL);  
  87.   assert(scr!=NULL);  
  88.   while(*dest)  
  89.   {  
  90.     dest++;  
  91.   }  
  92.   while(*dest=*scr)  
  93.   {  
  94.     scr++;  
  95.                 dest++;  
  96.   }  
  97.   return ret;  
  98. }  
  99. int main()  
  100. {  
  101.                  char str1[100]="I have " ;  
  102.                  char *str2="a dream!" ;  
  103.                 printf( "%s\n",my_strcat(str1,str2));  
  104.   system("pause");  
  105.   return 0;  
  106. }