模拟实现strlen

对于strlen:我们想必是不陌生的,熟悉的。话不多说,直接上代码

文章目录


前言

strlen函数可以求字符串的长度,同时我们通过模拟实现字符串可以提高我们对字符串的理解以及运用

一、strlen 的定义

Get string length

Returns the length of the C string str.

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).

This should not be confused with the size of the array that holds the string. For example:

char mystr[100]="test string";

defines an array of characters with a size of 100 chars, but the C string with which mystr has been initialized has a length of only 11 characters. Therefore, while sizeof(mystr) evaluates to 100, strlen(mystr) returns 11.

In C++, char_traits::length implements the same behavior.

二、使用步骤

1.引入库

代码如下(示例):

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <assert.h>
size_t my_strlen(const char* str)
{
	assert(str);
	char* start = str;
	char* end = str;
	while (*end != '\0')
	{
		end++;
	}
	return end - start;
}

int main()
{
	char arr[] = "abcdef";
	int len = my_strlen(arr);
	printf("%d\n", len);
}


总结

对于模拟实现strlen,我们首先要明白strlen 的定义以及基本的用法,strlen返回的是size_t, 而size_t的本质是typedef unsigned(即无符号的整型)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值