How to Find String Length in C

Use the strlen() function from the <string.h> header to find the length of a null-terminated string in C. It counts the bytes before the terminating null character, \0. Spaces and other bytes within the string are included, but the null terminator itself is not.

For example, strlen("united kingdom") returns 14: six letters, one space, and seven more letters. The array storing this string requires at least 15 bytes because it must also contain \0.

strlen() Syntax for Finding C String Length

The original syntax demonstration is shown below.

</>
Copy
 size strlen(const char *str);

In standard C, the actual return type is size_t, not size. The correct declaration is:

</>
Copy
size_t strlen(const char *str);
  • str points to the first character of a valid null-terminated string.
  • size_t is an unsigned integer type used for object sizes and counts.
  • strlen() returns the number of bytes before the first \0.

Use the %zu conversion specifier with printf() when printing a size_t value.

</>
Copy
#include <stdio.h>
#include <string.h>

int main(void) {
    const char text[] = "united kingdom";
    size_t length = strlen(text);

    printf("Length = %zu\n", length);
    return 0;
}
Length = 14

What strlen() Counts in a C String

strlen() starts at the address passed to it and examines successive bytes until it encounters the first null character. This leads to several useful rules:

  • Letters, digits, punctuation, and spaces before \0 are counted.
  • The terminating \0 is not counted.
  • An empty string contains only \0, so strlen("") returns 0.
  • An embedded null character ends the part treated as the C string.
  • The function must inspect the string to determine its length; it does not know the array capacity.
</>
Copy
#include <stdio.h>
#include <string.h>

int main(void) {
    char text[] = {'A', 'B', '\0', 'C', 'D', '\0'};

    printf("String length = %zu\n", strlen(text));
    printf("Array size = %zu\n", sizeof text);
    return 0;
}
String length = 2
Array size = 6

strlen(“”) and strlen(NULL) Produce Different Results

strlen("") is valid and returns zero because "" is an empty string containing a terminating null character. In contrast, strlen(NULL) passes a null pointer rather than a pointer to a string. Doing so causes undefined behavior; it does not reliably return zero.

If a pointer might be null, check it before calling strlen():

</>
Copy
size_t length_if_present(const char *text) {
    return text != NULL ? strlen(text) : 0;
}

String Length Without a Null Terminator

Calling strlen() on a character array that has no accessible null terminator causes undefined behavior. The function continues reading beyond the intended array while looking for \0. It may appear to return a value, read unrelated memory, or cause the program to fail.

The same requirement applies when an array is printed with printf("%s", text). Both operations expect a valid null-terminated string. See the existing UndefinedBehavior reference for the general concept.

C Programs for Calculating String Length

The following examples cover the standard library function, a loop, pointer traversal, and recursion.

  1. Find String Length using strlen() function
  2. Finding String Length in C programming using recursion
  3. Finding String Length in C programming using pointers

Find String Length with strlen()

The historical example below calls strlen() after reading a line. It is retained unchanged, but modern C code should include <string.h>, use fgets() instead of the removed gets() function, and print the result with %zu.

C Program

</>
Copy
#include <stdio.h>
int main() {
	char s[100];
	gets(s);
	printf("Length = %d\n", strlen(s));
	return 0;
}

Output

united kingdom    //given input
Length = 14

Find the Length of Input Read with fgets()

fgets() stores the newline when it fits in the array. Remove that newline before calculating the length if it should not be considered part of the user’s text.

</>
Copy
#include <stdio.h>
#include <string.h>

int main(void) {
    char text[100];

    printf("Enter a string: ");
    if (fgets(text, sizeof text, stdin) == NULL) {
        return 1;
    }

    text[strcspn(text, "\n")] = '\0';
    printf("Length = %zu\n", strlen(text));

    return 0;
}

strcspn(text, "\n") returns the position of the first newline, or the position of \0 if no newline is present. Assigning \0 at that position safely removes the newline when found.

Find String Length Without strlen() Using a for Loop

A loop can count characters until it reaches the terminating null character. This demonstrates the operation performed conceptually by strlen().

</>
Copy
#include <stdio.h>

int main(void) {
    const char text[] = "C programming";
    size_t length;

    for (length = 0; text[length] != '\0'; length++) {
        /* Count each byte before the null terminator. */
    }

    printf("Length = %zu\n", length);
    return 0;
}
Length = 13

Find String Length Using Recursion

A recursive solution is useful for demonstrating recursion, but an iterative loop or strlen() is generally more direct. The historical program below is retained unchanged. Its function combines a static counter, indexing, and pointer advancement in a way that can skip characters, and it uses the unsafe gets() function.

C Program

</>
Copy
#include <stdio.h>
int strlength(char* s);
int main() {
	char s[100];
	gets(s);
	printf("Length = %d\n", strlength(s));
	return 0;
}

int strlength(char *s) {
	static int c= 0;
	while (s[c] != '\0') 
	{
	c++;
	strlength(s+1);
	}

	return c;
}

Output

united kingdom    //given input
Length = 14

Correct Recursive Function for C String Length

A recursive length function needs one base case and one recursive step. It should not use a static counter because static state would make later calls produce incorrect results.

</>
Copy
#include <stdio.h>
#include <stddef.h>

size_t string_length_recursive(const char *text) {
    if (*text == '\0') {
        return 0;
    }

    return 1 + string_length_recursive(text + 1);
}

int main(void) {
    const char text[] = "united kingdom";
    printf("Length = %zu\n", string_length_recursive(text));
    return 0;
}

Find String Length Using Pointers

A pointer-based function advances through the string until it reaches \0. The historical example below demonstrates this traversal, although its input should be updated from gets() to fgets() in modern code.

C Program

</>
Copy
#include <stdio.h>
int strlength(char* s);
int main() {
	char s[100];
	gets(s);
	printf("Length = %d\n", strlength(s));
	return 0;
}

int strlength(char *s) {
	int c= 0;
	while (*s != '\0') 
	{
		c++;
		s++;
	}
	return c;
}

Output

united kingdom    //given input
Length = 14

Pointer-Based String Length Function with size_t

</>
Copy
#include <stddef.h>

size_t string_length(const char *text) {
    const char *current = text;

    while (*current != '\0') {
        current++;
    }

    return (size_t)(current - text);
}

The difference between the final pointer and the initial pointer is the number of bytes traversed. As with strlen(), text must point to a valid null-terminated string.

strlen() Versus sizeof for C Strings

strlen() reports the length of the null-terminated string currently stored in an array. sizeof reports the storage size of the array when the array type is still available.

</>
Copy
#include <stdio.h>
#include <string.h>

int main(void) {
    char text[20] = "hello";

    printf("strlen(text) = %zu\n", strlen(text));
    printf("sizeof text = %zu\n", sizeof text);
    return 0;
}
strlen(text) = 5
sizeof text = 20

Inside a function parameter declared as char text[], the parameter is adjusted to a pointer. In that function, sizeof text gives the size of the pointer, not the original array capacity. Pass the capacity as a separate argument when the function needs it.

Bytes, Characters, and UTF-8 String Length in C

strlen() counts bytes, not necessarily user-perceived characters. For plain ASCII text, one character occupies one byte, so the values usually match. In UTF-8, one encoded character may occupy multiple bytes. Therefore, the value returned by strlen() for UTF-8 text can be greater than the number of displayed characters.

Counting Unicode characters or grapheme clusters requires encoding-aware processing. strlen() alone cannot provide that count.

Common C String Length Mistakes

  • Counting the terminator: strlen() excludes \0, although the array needs storage for it.
  • Passing NULL: a null pointer is not an empty string and cannot be passed safely to strlen().
  • Using an unterminated array: strlen() requires a reachable \0 within valid memory.
  • Printing with %d: the return type is size_t, so use %zu.
  • Leaving the input newline: fgets() may include \n, which increases the reported length by one.
  • Confusing length with capacity: use strlen() for the stored string length and sizeof for an array’s compile-time storage size.
  • Using gets(): it cannot limit input and was removed from the C standard; use fgets().
  • Treating bytes as Unicode characters: multibyte encodings require encoding-aware counting.

Frequently Asked Questions About String Length in C

How do I find string length in C using strlen()?

Include <string.h> and call strlen(string). Store the result in a size_t variable or print it with %zu. The string must end with \0.

How do I find string length in C without strlen()?

Initialize a size_t counter to zero and advance through the array while string[counter] != '\0'. The final counter value is the string length in bytes.

Does strlen() include spaces and the null character?

It includes spaces before the string terminator, but it does not include the terminating \0.

What is the difference between strlen() and sizeof in C?

strlen() examines a null-terminated string and returns the number of bytes before \0. sizeof returns the storage size of an object or type. For a character array, that storage can be larger than the string currently stored in it.

Can strlen() count UTF-8 characters?

strlen() counts UTF-8 code-unit bytes before \0, not displayed characters. UTF-8 characters that use multiple bytes make the byte length greater than the visible character count.

C String Length Editorial QA Checklist

  • Confirm that the strlen() return type is identified as size_t.
  • Use %zu when a string length is printed with printf().
  • State that strlen() excludes \0 but includes spaces.
  • Verify that every measured character array has a reachable null terminator.
  • Do not describe strlen(NULL) as a valid empty-string check.
  • Distinguish stored string length from array capacity and pointer size.
  • Remove or account for the newline retained by fgets().
  • Identify strlen() as a byte-counting function when discussing UTF-8 text.
  • Avoid presenting gets() as safe input code.

Choosing a C String Length Method

Use strlen() for ordinary null-terminated strings. A loop or pointer-based function is useful when learning how the count works, while recursion adds unnecessary call overhead for this task. Always provide a valid null-terminated string, store the result as size_t, and remember that the result is a byte count. Continue with the C Tutorial for related C programming topics.