Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use strlen and sizeof to calculate the length of string

Shulou Source: shulou.com Published: 2022-06-03 05:32:43 10月05日 Update

This article will explain in detail how to use strlen and sizeof to calculate the length of strings. The content of the article is of high quality, so the editor shares it for you as a reference. I hope you will have some understanding of the relevant knowledge after reading this article.

First, strlen is a function, sizeof is an operation operator, and the result type is size_t, that is, the unsignedint type. Most compilers calculate sizeof at compile time, while strlen results can only be calculated at run time.

For the following statement:

Char*str1= "asdfgh"

Charstr2 [] = "asdfgh"

Charstr3 [8] = {'axiaqingjinyuanjiaoyuanzhangjiaoyuanzhongyuanzhongyuanzhongyuanzhongyuanzhongyuanzhongyuanzhongyuanzhongyuanzhongyuanzhongyuanzhongyuanzhongyuanzhongyuanzhongyuanzhong (charstr3) = {' axiaqiao

Charstr4 [] = "as\ 0df"

The result of the execution is:

Sizeof (str1) = 4 th strlen (str1) = 6

Sizeof (str2) = 7 th strlen (str2) = 6

Sizeof (str3) = 8 th strlen (str3) = 3

Sizeof (str4) = 6 th strlen (str4) = 2

Str1 is a character pointer variable, and sizeof gets the address space occupied by the pointer, and the 32-bit operating system corresponds to 4 bytes, so the result is that 4-bit strlen returns the length of the string. If\ 0 ends,\ 0 itself is not counted, so the result is 6.

Str2 is an array of characters whose size is determined by the string constant "asdfgh". Sizeof gets the amount of memory occupied by the array, including\ 0 at the end of the string, so the result returns 6.

Str3 is also an array of characters, but the size is determined to be 8, so the result obtained by sizeof is the number of characters before\ 0, that is, 3.

Str4 is an array of constant characters. Sizeof gets the total number of characters, that is, 6 characters. Strlen calculates to the end of\ 0, so it returns 2.

To sum up, sizeof calculates the size of the variable, while strlen calculates the length of the string. The former is not affected by the character\ 0, while the latter uses\ 0 as the basis for determining the length.

On how to use strlen and sizeof string length operation to share here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Tags: Character result string length size array operation content variable constant pointer article time more knowledge space article type compilation good Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology vpn macOS Docker MySQL