计算长度 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("Argument missing.");
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!"
运行时,程序将输出 The length of the second argument is 13.
,因为字符串 Hello, world!
长度为 13 个字符。
strlen
计算字符串开头的所有字节,但不包括终止 NUL 字符'\0'
。因此,只有在保证字符串被 NUL 终止时才能使用它。
另外请记住,如果字符串包含任何 Unicode 字符,strlen
将不会告诉你字符串中有多少字符(因为某些字符可能是多个字节长)。在这种情况下,你需要自己计算字符( 即代码单元)。考虑以下示例的输出:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char asciiString[50] = "Hello world!";
char utf8String[50] = "Γειά σου Κόσμε!"; /* "Hello World!" 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
"Hello world!" is 12 bytes
"Γειά σου Κόσμε!" is 27 bytes