0
0
CHow-ToBeginner · 3 min read

How to Use strlen in C: Syntax and Examples

In C, use the strlen function from string.h to find the length of a string. It returns the number of characters before the null terminator \0 in a char array.
📐

Syntax

The strlen function has this syntax:

  • size_t strlen(const char *str);

Here, str is a pointer to the string you want to measure. The function returns the length as a size_t number, which counts characters until the null \0 character.

c
size_t strlen(const char *str);
💻

Example

This example shows how to use strlen to get the length of a string and print it:

c
#include <stdio.h>
#include <string.h>

int main() {
    char message[] = "Hello, world!";
    size_t length = strlen(message);
    printf("The length of the string is: %zu\n", length);
    return 0;
}
Output
The length of the string is: 13
⚠️

Common Pitfalls

Common mistakes when using strlen include:

  • Passing a NULL pointer causes a crash.
  • Using strlen on non-null-terminated arrays leads to undefined behavior.
  • Confusing strlen with the size of the array; strlen counts characters until \0, not the total array size.

Always ensure your string is properly null-terminated before calling strlen.

c
#include <stdio.h>
#include <string.h>

int main() {
    char not_string[5] = {'H', 'e', 'l', 'l', 'o'}; // No null terminator
    // This is unsafe and may cause unexpected results
    // size_t len = strlen(not_string); // Don't do this

    char proper_string[] = "Hello"; // Null-terminated
    size_t len = strlen(proper_string); // Correct usage
    printf("Length: %zu\n", len);
    return 0;
}
Output
Length: 5
📊

Quick Reference

FunctionDescription
strlen(const char *str)Returns the length of the string before the null terminator
Requires Include this header to use strlen
Returns size_tUnsigned integer type for length
Input must be null-terminatedOtherwise behavior is undefined

Key Takeaways

Use strlen to find the length of a null-terminated string in C.
Always include string.h to use strlen.
Do not use strlen on arrays without a null terminator.
Passing NULL to strlen causes a crash.
The returned length excludes the null terminator character.