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!",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] = "你好,世界!";
    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