C语言的strlen函数怎么使用

发布时间:2022-10-21 15:17:38 作者:iii
来源:亿速云 阅读:255

今天小编给大家分享一下C语言的strlen函数怎么使用的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。

C语言中的字符串函数有如下这些

接下来看看如何实现它们

获取字符串长度

strlen

我们看看文档是怎样说的,如下

strlen文档

size_t strlen ( const char * str );

Get string length

获取字符串长度

Returns the length of the C string str.

返回C字符串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).

C字符串长度是由'\0'来确定的,也就是说从字符串的第一个开始只要遇到'\0'就结束长度计算(不包含'\0')

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 100strlen(mystr) returns 11.

定义一个大小为100的数组mystr,然后mystr 就已经被初始化为一个长度为11的字符串了。所以呢, sizeof(mystr) 会得出 100, 而strlen(mystr) 会返回 11.

综上,可以知道

  1. 字符串已经 '\0' 作为结束标志,strlen函数返回的是在字符串中 '\0' 前面出现的字符个数(不包含 '\0' )。

  2. 该函数只认'\0',参数指向的字符串必须要以 '\0' 结束。

  3. 注意函数的返回值为size_t,是无符号的

实现

strlen函数的实现有好几种。

比如

  1. 计数器的方法

  2. 递归

  3. 指针 - 指针

接下来一一实现。

1. 计数器:使用一个变量来记录 - count

断言指针不为空是个好习惯~

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

就一直找'\0',当*str不是'\0'时,就count++,str++,直到遇到'\0'停止,然后返回count就是长度了。

2. 递归

断言指针不为空是个好习惯~

int my_strlen(char* str)
{
    assert(str != NULL);
    char* p = str;
    while(*p == '\0')
    {
        return 0;
    }
    return 1 + my_strlen(p + 1);
}

比如传入的str地址为 1000

那么 1 + my_strlen(p + 1) 中,p + 1,指针偏移后就是1001,以此类推。

1 + 1 + my_strlen(p + 1)

1 + 1 + 1 + my_strlen(p + 1)

1 + 1 + 1 + 1 + my_strlen(p + 1)

...

1 + 1 + 1 + 1 + ... + 0

最终就可以得出长度。

3. 指针-指针

断言指针不为空是个好习惯~

int my_strlen(char* str) 
{
    assert(str != NULL);
	char* p = str;
	while (*p != '\0') 
	{
		p++;
	}
	return p - str;
}

把指针str的地址赋值给一个新的指针p,str作为指向起始地址的指针,不改变它,记录起始地址。

然后通过指针p进行查找'\0',判断当前字符是否为'\0',不是就进行p++,然后继续判断下一个字符,如此循环,直到指针p找到'\0',然后用 当前的指针p 减去 起始指针str 进行返回,就是长度了。

以上就是“C语言的strlen函数怎么使用”这篇文章的所有内容,感谢各位的阅读!相信大家阅读完这篇文章都有很大的收获,小编每天都会为大家更新不同的知识,如果还想学习更多的知识,请关注亿速云行业资讯频道。

推荐阅读:
  1. strlen() 函数
  2. php中strlen函数的使用方法

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c语言 strlen

上一篇:怎么使​用Python代码实现线性表的顺序存储结构

下一篇:C语言的strcpy函数如何使用

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》