C Program to Find the Length of a String Without strlen()

C Program to Find the Length of a String Without strlen()

Finding the length of a string is one of the most basic tasks in C programming. While the standard library provides the strlen() function for this purpose, understanding how to calculate the length manually is an essential exercise for beginners. This teaches how strings are stored in memory and how to navigate character arrays.

In this tutorial, we will write a C program to find the length of a string without using strlen(). By the end, you will be confident in handling strings and understanding the underlying logic of strlen().

What Is A String?

A string in C is essentially an array of characters that ends with a null character (\0). This null character marks the end of the string and is essential for determining its length.

Calculating the length manually involves traversing the string from the first character until the null character is encountered. This approach gives you a deeper understanding of how strings work in C and how memory is accessed when processing characters.

Understanding the Problem

The problem is to read a string from the user and count the number of characters until the null terminator \0 is found. It is important to handle inputs carefully, including spaces, tabs, or special characters, and to ensure the program does not access memory beyond the string’s bounds.

The key concepts are:

  • A string is an array of characters.
  • The last character of every string is \0.
  • Counting characters until the null terminator gives the string’s length.

Program 1: Using a Simple for Loop

We start with the simplest method using a for loop. This method iterates through each character of the string, counting characters until the null terminator is encountered.

#include <stdio.h>

int main() {

    char str[100];
    int length = 0;

    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);

    for(int i = 0; str[i] != '\0'; i++) {

        if(str[i] != '\n') {
            length++;
        }

    }

    printf("Length of the string: %d\n", length);

    return 0;

}

This program reads the input using fgets() to safely handle spaces. The for loop starts at index 0 and checks each character. If it’s not the null character (\0), the counter length is incremented. We also ignore the newline character \n that fgets() may include.

Program 2: Using a while Loop

Next, we use a while loop. This is another straightforward way to traverse the string and count its length.

#include <stdio.h>

int main() {

    char str[100];
    int length = 0;

    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);

    int i = 0;

    while(str[i] != '\0') {

        if(str[i] != '\n') {
            length++;
        }

        i++;

    }

    printf("Length of the string: %d\n", length);

    return 0;

}

The logic is similar to the for loop method. The loop continues until the null character is encountered, incrementing the length counter for each valid character. Using while can make it easier to modify or add conditions in complex programs.

Program 3: Using Pointer Arithmetic

Pointer arithmetic allows us to traverse the string using a pointer instead of an array index. This method introduces pointers, an important concept in C programming.

#include <stdio.h>

int main() {

    char str[100];
    char *ptr;
    int length = 0;

    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);

    ptr = str;

    while(*ptr != '\0') {

        if(*ptr != '\n') {
            length++;
        }

        ptr++;

    }

    printf("Length of the string: %d\n", length);

    return 0;

}

Here, ptr points to the start of the string. The loop checks the value pointed to by ptr and increments both the pointer and the length counter until the null character is found.

Program 4: Using Recursion

Finally, recursion provides a way to calculate the string length without using loops. It demonstrates dividing the problem into smaller subproblems.

#include <stdio.h>

int stringLength(char *str) {

    if(*str == '\0' || *str == '\n') {
        return 0;
    }

    return 1 + stringLength(str + 1);

}

int main() {

    char str[100];

    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);

    int length = stringLength(str);

    printf("Length of the string: %d\n", length);

    return 0;

}

The recursive function stringLength checks if the current character is the null terminator or newline. If so, it returns 0. Otherwise, it returns 1 plus the length of the rest of the string by calling itself with the next character.

Performance Comparison

The temporary array method is simple and fast for small arrays but uses extra memory. One-by-one rotation is memory-efficient but slow for large arrays due to repeated shifts. The reversal algorithm is both fast and memory-efficient, making it suitable for most cases. Using memcpy() is optimal for very large arrays when performance is critical.

MethodTime ComplexitySpace ComplexityNotes
for LoopO(n)O(1)Simple and easy to understand
while LoopO(n)O(1)Readable and straightforward
Pointer ArithmeticO(n)O(1)Efficient and demonstrates pointer usage
RecursionO(n)O(n)Elegant, but uses call stack memory

Which Method Should You Use?

For beginners, the for loop method is easiest to understand. It clearly shows how the program checks each character in sequence.

The while loop is suitable if you prefer a loop that separates initialization and iteration, making it easier to modify conditions.

The pointer method is ideal for students who want to learn memory addressing and pointers in C. It is often used in more advanced programs or performance-critical applications.

The recursive method is elegant and shows how a problem can be solved by breaking it down into smaller subproblems. It is not the most memory-efficient for very large strings, but it is excellent for teaching recursion concepts.

FAQs

1. Can this program handle empty strings?
Yes. If the input is empty, the program correctly reports a length of zero.

2. Why do we ignore \n in fgets()?
fgets() includes the newline character when the user presses Enter. Counting it can give an incorrect length, so we exclude it.

3. Can we calculate length without loops?
Yes, recursion provides a way to calculate length without explicit loops, though it uses call stack memory.

4. Is the pointer method faster than a loop?
Performance is nearly the same for small strings. Pointer arithmetic is more advanced and can be slightly faster for large arrays.

Conclusion

Finding the length of a string without strlen() teaches beginners how strings are stored in memory and how to traverse character arrays safely.

You learned four methods: using a for loop, a while loop, pointer arithmetic, and recursion. Each method is efficient in its own way and helps you understand different programming concepts. By practicing these methods, you gain a solid foundation for working with strings in C programming.

References & Additional Resources

A curated collection of textbooks, tutorials, and documentation for learning string length determination, pointers, and input handling in C.

  1. Kernighan, Brian W., and Dennis M. Ritchie. The C Programming Language, 2nd Edition, Prentice Hall, 1988 – The foundational text covering strings, pointers, arrays, and core C programming concepts.
  2. GeeksforGeeks: Length of a String Without Using strlen() Function in C – Explains methods to calculate the length of a string in C without using strlen().
  3. Tutorialspoint: C Strings – Overview of string declaration, initialization, and common operations in C.
  4. Cprogramming.com: Pointers in C – Beginner-friendly guide on using pointers for string and array manipulation.
  5. cplusplus.com: fgets() Function – Documentation for fgets() used to safely read strings from input in C.
Scroll to Top