Several Methods of Calculating String Length in C Language
The C language calculates the length of a string, either manually or using a library function or the sizeof() operator.
- custom function to find length
- Use strlen() function
- Using the sizeof() operator
custom function
int cont_str(char *s)
{
int i = 0;
while ( str[i++] != '\0')
;
return i;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
Use the strlen() function in the string header file
strlen(str); //假设str为待求的字符串数组名
- 1
- 2
Using the sizeof() operator
sizeof(str)/sizeof(str[0]); //假设str为待求的字符串数组名
- 1
- 2
Notice:
- The length of the string obtained by the strlen() function is a valid length, neither including the end character '\0' at the end of the string;
- The length obtained by the sizeof() operator includes the terminator '\0' at the end of the string;
- When using sizeof() inside the function to solve the length of the character array passed in by the formal parameter of the function, the result obtained is the length of the pointer , which corresponds to the number of bytes of the variable, not the length of the string, which must be careful. 【1】
Reference: http://bbs.fishc.com/thread-2502-1-1.html