1. 处理函数

  • strlen()
  1. strlen(s),sizeof(s):test = “hello\0world” ==> 5 “hello\0world” ==> 12
  2. 在字符串连接和复制后,strlen(s)会发生变化
  • strcpy():覆盖+添0,返回char* dst
  • strcat():在dst后覆盖+添0,返回char* dst

字符串处理.png

  • strcmp():字符串相减


  • strncpy,strncats,strncmp

**

2. 复合赋值


while(dst++)

dst
++
判断

dst++ = src++

dst
++
src
++
赋值

  1. while(*s) //指向0
  2. while(*++s)//指向0
  3. while(*s++)//指向0的下一个

复合运算.PNG

MyStrFunc:

  1. #include <stdio.h>
  2. #include <string.h>
  3. int MyStrlen(const char* s)
  4. {
  5. //下标
  6. int cnt = 0;
  7. for(int i=0; s[i]; i++)
  8. cnt++;
  9. return cnt;
  10. //
  11. // //下标优化
  12. // int i = 0;
  13. // while(s[i++]);
  14. // return --i;
  15. //
  16. // //指针
  17. //// int cnt = 0;
  18. //// while(*s++)
  19. //// cnt++;
  20. //// return cnt;
  21. //
  22. // //指针
  23. //// char const* start = s;
  24. //// while(*s++);
  25. //// return s-start-1;
  26. }
  27. char* MyStrcp(char* dst, const char* src)
  28. {
  29. //下标
  30. // int i;
  31. // for(i=0; src[i]; i++)
  32. // {
  33. // dst[i] = src[i];
  34. // }
  35. // dst[i] = 0;
  36. //
  37. // return dst;
  38. // //下标优化
  39. // int i = 0;
  40. // while(dst[i]=src[i++]);
  41. // return dst;
  42. //指针
  43. char* p = dst;
  44. while(*dst++ = *src++);
  45. return p;
  46. }
  47. char* MyStrcat(char* dst, const char* src)
  48. {
  49. //下标
  50. int len = strlen(dst);
  51. int i;
  52. for(i=0; src[i]; i++){
  53. dst[len+i] = src[i];
  54. }
  55. dst[len+i] = 0;
  56. return dst;
  57. //指针
  58. // char* p = dst;
  59. // while(*++dst);
  60. // while(*dst++ = *src++);
  61. // return p;
  62. }
  63. int MyStrcmp(const char* s1, const char* s2)
  64. {
  65. for(int i=0; s1[i] && s2[i]; i++)
  66. {
  67. if(s1[i]!=s2[i])
  68. return s1[i]-s2[i];
  69. }
  70. return 0;
  71. }
  72. int main()
  73. {
  74. char s[15] = {'h','i',0,0,0,0,'h','e','r','e'};
  75. // printf("%d\n", MyStrlen(s));
  76. char src[10] = "world";
  77. // puts(MyStrcp(s,src));
  78. char test[5] = "test";
  79. // puts(MyStrcat(s,test));
  80. // printf("%d %d\n", strcmp(s,src), MyStrcmp(s,src));
  81. return 0;
  82. }