[C] strlen of library function

Get string length

  Returns the length of the C string.

  The length of a C string is determined by the terminating null-character: A c string is as long as the number of characters between the beginning of the string and the terminating null character (without including the terminating null character itself).

  The above content is the introduction of the strlen function on the C++ official website. It can be seen that the strlen function is used to calculate the length of the string, which is the same as the number of characters between the beginning of the string and the terminating null character (excluding the terminating null character itself).

  Next, four ways to implement the strlen function are given:

1. Create a temporary variable as a counter to count

/*
* Function name: MyStrlen
*
* Function: return the length of the C string
* Method 1: Create a temporary variable to count as a counter
*
* Entry parameter: str
*
* Exit parameter: length
*
* return type: int
*/

int MyStrlen(const char * str)
{
	int length = 0;

	assert(NULL != str);

	while ('\0' != *str)
	{
		length++;
		str++;
	}

	return length;
}

2. Pointer - Pointer

/*
* Function name: MyStrlen
*
* Function: return the length of the C string
* Method 2: Pointer-Pointer
*
* Entry parameter: start
*
* Exit parameters: end - start
*
* return type: int
*/

int MyStrlen(const char * start)
{
	const char * end = start;

	assert(NULL != start);

	while ('\0' != *end)
	{
		end++;
	}

	return (end - start);
}
3.递归
/*
*	函数名称:MyStrlen
*
*	函数功能:返回C字符串的长度
*            方法3:不创建临时变量,使用递归
*
*	入口参数:str
*
*	出口参数:0 or 1+MyStrlen(str+1)
*
*	返回类型:int
*/

int MyStrlen(const char * str)
{
	assert(NULL != str);

	if ('\0' == *str)
	{
		return 0;
	}
	else
	{
		return (1 +	MyStrlen(str+1));
	}
}

4.一行代码实现strlen

  利用逗号表达式以及三目操作符即可实现,实际上还是递归。

/*
*	函数名称:MyStrlen
*
*	函数功能:计算字符串长度
*
*	入口参数:str
*
*	出口参数:0 or 1 + MyStrlen(str + 1)
*
*	返回类型:int
*/

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

主函数

#define _CRT_SECURE_NO_WARNINGS 1

/*
* Copyright (c) 2018, code farmer from sust
* All rights reserved.
*
* 文件名称:MyStrlen.c
* 功能:返回C字符串的长度,
*      C字符串的长度与字符串开头和终止空字符之间的字符数相同(不包括终止空字符本身)
*
* 当前版本:V1.0
* 作者:sustzc
* 完成日期:2018年4月20日13:54:49
*/

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

int main(void)
{
	char *str = "abcdef";

	printf("string length: %d\n", MyStrlen(str));

	return 0;
}

输出结果


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325524547&siteId=291194637