C语言中字符串的长度
2014-09-16 10:25
162 查看
C语言中没有定义字符串的基本的数据类型,通常用字符数组或者用符号常量(#define)来表示。
sizeof:sizeof运算符以字节为单位统计字符串的长度,会包含编译器自动加到字符串后面的空字符(字符串结束的标志‘\0'),实际上为编译器分配给该字符数组变量的内存大小。
strlen():strlen函数以字符为单位统计字符的长度,不会包含字符串结束标志的空字符。
例子:
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.
相关文章推荐
- 关于C语言的一个“巨大”发现~字符串长度的计算
- 【C语言】字符串中的转义字符与字符串的长度
- c语言字符串长度的计算方法
- c语言输出字符串中最大对称子串长度的3种解决方案
- c语言输出字符串中最大对称子串长度的3种解决方案
- C语言的字符串处理-长度(23)
- C语言 realloc为什么要有返回值,realloc返回值详解/(解决任意长度字符串输入问题)。
- C语言实现字符串拷贝 拷贝指定长度字符串 字符串连接
- C语言字符串的长度与大小
- C语言 - 得到字符串的长度
- C语言字符串比较的实现及求字符串长度的实现
- C语言:使用链表实现的可变长度字符串处理函数
- 使用C语言计算utf-8字符串长度
- C语言检测字符串长度
- C语言 数组、字符串长度及所占内存
- strlen 得到字符串长度,c语言实现
- C语言字符串长度
- 使用C语言计算utf-8字符串长度
- C语言计算字符串的长度strlen