How to Find Length of String in C: Simple Guide
In C, you find the length of a string using the
strlen() function from string.h. It counts characters until the null character '\0' that ends the string.Syntax
The strlen() function is declared in the string.h header. It takes a const char * (a pointer to a string) and returns the length as size_t, which is an unsigned integer type.
strlen(str): Returns the number of characters instrbefore the null terminator.
c
size_t strlen(const char *str);
Example
This example shows how to use strlen() to find and print the length of a string.
c
#include <stdio.h> #include <string.h> int main() { char greeting[] = "Hello, world!"; size_t length = strlen(greeting); printf("Length of string: %zu\n", length); return 0; }
Output
Length of string: 13
Common Pitfalls
Common mistakes when finding string length in C include:
- Not including
string.h, causingstrlen()to be undefined. - Passing a pointer that is not null-terminated, which leads to undefined behavior or crashes.
- Using
sizeofon a pointer instead ofstrlen(), which returns the pointer size, not string length.
c
#include <stdio.h> #include <string.h> int main() { char *str = "Hello"; // Wrong: sizeof(str) returns size of pointer, not string length printf("Wrong length: %zu\n", sizeof(str)); // Right: use strlen to get string length printf("Correct length: %zu\n", strlen(str)); return 0; }
Output
Wrong length: 8
Correct length: 5
Quick Reference
Remember these tips when working with string lengths in C:
- Always include
<string.h>to usestrlen(). strlen()counts characters until the null terminator'\0'.- Do not use
sizeofon pointers to get string length. - Strings must be properly null-terminated.
Key Takeaways
Use
strlen() from string.h to find string length in C.strlen() counts characters until the null terminator '\0'.Never use
sizeof on a pointer to get string length.Always ensure strings are null-terminated to avoid errors.
Include
string.h to avoid compilation errors with strlen().