C Program to Find the Length of a String

Updated on September 30, 2024
Find the Length of a String header image

Introduction

A string in C is a sequence of characters terminated by a null character '\0'. Determining the length of a string is a fundamental operation in many programming tasks, as it is often necessary to know the string's length to manipulate it correctly, such as in loops, memory allocation, and comparison operations.

In this article, you will learn how to find the length of a string in C using different methods. Understand how to implement standard library functions and custom functions for this purpose through step-by-step examples.

Using the strlen() Function

Standard Library Approach

  1. Include the string.h library which contains the strlen() function.

  2. Declare a string initialized with a character array.

  3. Use strlen() to find the length of the string.

    c
    #include <stdio.h>
    #include <string.h>
    
    int main() {
        char str[] = "Hello World";
        int length = strlen(str);
        printf("Length of the string: %d\n", length);
        return 0;
    }
    

    This code initializes str with "Hello World" and uses strlen() to compute the length, which excludes the null terminator. The function returns the number of characters before the null character.

Implementing a Custom Function

Manual Loop Method

  1. Define a function that takes a character array as an argument.

  2. Initialize a counter to zero.

  3. Use a while loop to increment the counter until the null character is encountered.

  4. Return the counter as the length of the string.

    c
    #include <stdio.h>
    
    int stringLength(const char str[]) {
        int length = 0;
        while (str[length] != '\0') {
            length++;
        }
        return length;
    }
    
    int main() {
        char str[] = "Example String";
        int length = stringLength(str);
        printf("Length of the string: %d\n", length);
        return 0;
    }
    

    This function, stringLength, manually iterates through the character array str until it hits the null terminator, counting each character. It then returns the count, effectively giving the length of the string.

Conclusion

Determining the length of a string in C can be done effectively using the standard library's strlen() function or by implementing a custom function that iterates through the string. Both methods are essential for handling strings in C, whether for manipulation, comparison, or other operations. By understanding how to measure string length, you ensure your string-handling code is robust and efficient.