天天看點

【C語言】三種方法實作strlen函數

#include <stdio.h>
#include <assert.h>

int my_strlen1(const char *str)//指針相減
{
	assert(str);
	const char *ptr = str;
	while (*ptr++ != '\0')
	{
		;
	}
	return ptr - str - 1;
}
int my_strlen2(const char *str)//遞歸
{
	assert(str);
	while (*str != '\0')
	{
		return 1 + (strlen(str + 1));
	}
}
int my_strlen3(const char *str)//計數器
{
	assert(str);
	int count = 0;
	while (*str != '\0')
	{
		count++;
		str++;
	}
	return count;
}
int main()
{
	char *str = "abcdefd";
	printf("%d\n", my_strlen1(str));
	printf("%d\n", my_strlen2(str));
	printf("%d\n", my_strlen3(str));
	system("pause");
	return 0;
}
           
【C語言】三種方法實作strlen函數
【C語言】三種方法實作strlen函數

繼續閱讀