(standard c libraries translation )strlen

来源:互联网 发布:虚拟机linux 编辑:程序博客网 时间:2024/04/29 03:07
strlen - calculate the length of a string
计算字符串的长度

所需头文件
#include <string.h>

size_t strlen(const char *s);

The strlen() function calculates the length of the string s, excluding the terminating null byte ('\0').
The strlen() function returns the number of bytes in the string s.
strlen函数计算字符串s的长度,不包括字符串结束符\0

返回字符串的s的字节数


testcase如下:

#include <stdio.h>#include <string.h>int main(void){char dest[20];const char *src = "hello world!";int tmp = 0, stmp = 0;tmp= strlen(src);printf("tmp = %d\n", tmp);stmp = sizeof(src);printf("stmp = %d\n", stmp);strcpy(dest, src);printf("dest = %s\n", dest);tmp = strlen(dest);printf("tmp = %d\n", tmp);stmp = sizeof(dest);printf("stmp = %d\n", stmp);return 0;}

运行结果如下:

cheny.le@cheny-ThinkPad-T420:~/cheny/testCode$ ./a.out
tmp = 12
stmp = 8
dest = hello world!
tmp = 12
stmp = 20

strlen很简单,没有什么好说的,唯一需要说一下的就是strlen跟sizeof的区别,strlen跟他定义说描述的那样,计算字符串的长度,不包括字符串结束符\0,所以不管存储字符串的是数组,还是一块由指针所指向的内存,都是返回字符串的长度,sizeof就不一样了,如果参数是指向字符串的指针,那么就返回指针的大小(在64位机器上是8个字节,32位上是4个字节),如果参数是数组名,那么就返回数组的大小(结构体相同)!

0 0