C语言中字符串的长度

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.out
Please input one strings: test
Your 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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值