#include <stdio.h> #include <stdlib.h> int my_strlen(const char *str) { char *tmp = str; //用tmp保存原指針的地址 while (*str) //str++直到‘\0’ { str++; } return str - tmp; //兩個指針相減,得到字符長度 } int main()
#include <stdio.h> int my_strlen(const char *ptr) { int len = 0; while (*ptr) { len++; //讀取一個字符串,計數器+1 ptr++; } return len; } int main() { char p[] = "abcdefg"; printf("%d\n",my_strlen(p)); return 0; }
{ char *p = "bit"; printf("%d\n", my_strlen(p)); system("pause"); return 0; } 方法二:計數器方式 方法三:數組
#include <stdio.h> #include <stdlib.h> int main() { char arr[]="hdffkfefewf"; int len = sizeof(arr) / sizeof(arr[0]); char *pstart = arr; char *pend = arr + len; printf("%d\n",pend - pstart); system("pause"); return 0;