方法一:
利用指針特性進行運算
windows
#include <stdio.h> #include <string.h> #include <windows.h> //計算字符串長度不用string函數 int strl(char* p,int sz) { int i; int count = 0; for (i=0;i<sz;i++) { printf("%d\n", *p); if (*p != '\0') { count =count + 1; p ++; } else { p ++; } } return count; } int main() { char ch[] = { 'a','b','\0' }; int sz = sizeof(ch) / sizeof(ch[0]); int a=strl(ch,sz); printf("%d \n", a); }
方法二:
兩個指針相減得位數:
數組
#include <stdio.h> #include <string.h> int strl(char* p, int sz) { char* start = p; char* end = p; while (*end != '\0') { end = end + 1; } return end- start; } int main() { char ch[] = { 'a','b','c','\0' }; int sz = sizeof(ch) / sizeof(ch[0]); //測試 /*printf("%d \n", sz);*/ int b = strl(ch, sz); printf("ch數組字符串長度:%d\n", b); }