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 爱生日祝福语简短独特