C语言中字符串的长度

来源:互联网 发布:python 字符串补零 编辑:程序博客网 时间:2024/05/21 17:43

C语言中没有定义字符串的基本的数据类型,通常用字符数组或者用符号常量(#define)来表示。

sizeof:sizeof运算符以字节为单位统计字符串的长度,会包含编译器自动加到字符串后面的空字符(字符串结束的标志‘\0'),实际上为编译器分配给该字符数组变量的内存大小。

strlen():strlen函数以字符为单位统计字符的长度,不会包含字符串结束标志的空字符。

例子:

[root@localhost c]$ cat test.c#include <stdio.h> //提供scanf()和printf()函数的原型#include <string.h> //提供strlen()函数的原型,其中还包含很多字符串处理的函数#define FEELING "It is bad day!" //定义符号常量,编译器会负责在该符号常量后面加上字符串结束标志void main(void){    char a[10]; //定义大小为10的字符数组    printf("Please input one strings: ");    scanf("%s", a); //读取完字符串后,scanf函数会自动加上字符串结束标志    printf("Your input strings is %s.\n", a);    printf("The sizeof of your input strings is %d.\n", sizeof(a)); //计算字符数组的长度,编译器分配给该字符数组的内存大小    printf("The strlen of your input strings is %d.\n", strlen(a)); //计算字符数组中实际字符的长度    printf("The sizeof of FEELING is %d.\n", sizeof(FEELING)); //计算字符常量的长度,包含字符串结束标志    printf("The strlen of FEELING is %d.\n", strlen(FEELING)); //计算字符常量实际的字符串的长度    printf("The length of array a is %d.\n", sizeof(a)/sizeof(a[0])); //计算字符数字的长度}
编译&运行:

[root@localhost c]$ gcc test.c[root@localhost c]$ ./a.outPlease input one strings: testYour input strings is test.The sizeof of your input strings is 10.The strlen of your input strings is 4.The sizeof of FEELING is 15.The strlen of FEELING is 14.The length of array a is 10.
0 0
原创粉丝点击