C语言计算长度:strlen()
示例
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv)
{
/* Exit if no second argument is found. */
if (argc != 2)
{
puts("参数丢失。");
return EXIT_FAILURE;
}
size_t len = strlen(argv[1]);
printf("The length of the second argument is %zu.\n", len);
return EXIT_SUCCESS;
}该程序计算其第二个输入参数的长度,并将结果存储在中len。然后将该长度打印到终端。例如,当使用参数运行时program_name"Hello,world!",Thelengthofthesecondargumentis13.由于字符串Hello,world!长度为13个字符,因此将输出程序。
strlen计算从字符串开头到结束NUL字符(但不包括)的所有字节'\0'。因此,仅在保证字符串以NUL终止时才可以使用它。
还请记住,如果字符串包含任何Unicode字符,strlen则不会告诉您字符串中有多少个字符(因为某些字符可能有多个字节长)。在这种情况下,您需要自己计算字符(即代码单位)。考虑以下示例的输出:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char asciiString[50] = "你好,世界!";
char utf8String[50] = "Γειά σου Κόσμε!"; /* "你好,世界!" in Greek */
printf("asciiString has %zu bytes in the array\n", sizeof(asciiString));
printf("utf8String has %zu bytes in the array\n", sizeof(utf8String));
printf("\"%s\" is %zu bytes\n", asciiString, strlen(asciiString));
printf("\"%s\" is %zu bytes\n", utf8String, strlen(utf8String));
}输出:
asciiString has 50 bytes in the array utf8String has 50 bytes in the array "你好,世界!" is 12 bytes "Γειά σου Κόσμε!" is 27 bytes
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短