C语言中求字符串长度的函数的几种实现方法

2020-01-06 19:08:38于丽

1.最常用的方法是创建一个计数器,判断是否遇到‘',不是''指针就往后加一。


int my_strlen(const char *str)
{
	assert(str != NULL);
	int count = 0;
	while (*str != '')
	{
		count++;
		str++;
	}
	return count;
}

2.不创建计数器,从前向后遍历一遍,没有遇到‘'就让指针向后加一,找到最后一个字符,记下来地址,然后用最后一个字符的地址减去起始地址,就得到了字符串的长度。


int my_strlen(const char *str)
{
	char *end = str;
	assert(str!=NULL);
	assert(end!=NULL);
	while (*end != '')
	{
		end++;
	}
	return end - str;
}

3.不创建计数器,递归实现。


int my_strlen(const char *str)
{
	assert(str != NULL);
	if (*str == '')
	{
		return 0;
	}
	else
	{
		return (1 + my_strlen(++str));
	}
}

也可以写成这样:


int my_strlen(const char *str)
{
	assert(str != NULL);
	return (*str == '') ? 0 : (my_strlen(++str) + 1);
}

或者这样:


int my_strlen(const char *str)
{
	assert(str != NULL);
	return (*str == '') ? 0 : (my_strlen(str+1) + 1);
}

这篇关于c语言中获取字符串长度的函数就介绍到这了,需要的朋友可以参考一下。


注:相关教程知识阅读请移步到C++教程频道。