做外貿(mào)在哪個(gè)網(wǎng)站北京百度推廣電話號(hào)碼
字符串是以‘\0’作為結(jié)束標(biāo)志,strlen函數(shù)的返回值是‘\0’前面的字符串的個(gè)數(shù)(不包括‘\0’)
注意
1,參數(shù)指向的字符串必須以‘\0’結(jié)束
2,函數(shù)的返回值必須以size_t,是無(wú)符號(hào)的
使用代碼
?
#include<stdio.h>
#include<string.h>
int main()
{char arr[] = "abcdef";int a = strlen(arr);printf("%d", a);return 0;
}?
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?結(jié)果運(yùn)行
strlen模擬實(shí)現(xiàn)
方法1
int my_strlen(const char * str)
{int count = 0;assert(str);while(*str){count++;str++;}return count;
}
方法2
int my_strlen(const char * str)
{assert(str);if(*str == '\0')return 0;elsereturn 1+my_strlen(str+1);
}
方法3
int my_strlen(char *s)
{assert(str);char *p = s;while(*p != ‘\0’ )p++;return p-s;
}
整體代碼
#include<stdio.h>
#include<assert.h>
int my_strlen(char* arr)
{assert(arr);char* p = arr;while (*p!= '\0')p++;return p - arr;
}int main()
{char arr[] = "abcdef";int a = my_strlen(arr);printf("%d", a);return 0;
}