Find Length of a String Without string.h and Loop in C



C provides libraries for string operations such as the string.h header file that contains a strlen() function, which counts the length of a string. Otherwise, a loop can be used to count the string length.

There are also different ways to find the length of a string apart from the above two methods. So, basically, in this article, we will learn how to find the length of a string without string.h and loop in C.

Find Length of a String Without string.h and Loop in C

There are the following ways to find the string's length without using the string.h and loop:

Using sprintf() Method

The sprintf() is the most straightforward method to find the length of the string in C without using the string.h and loop:

#include <stdio.h>
int main() {
   char str[] = "tutorialspoint";
   // Temporary buffer
   char buff[20];
   
   // length of string str
   int len = sprintf(buff, "%s", str);
   
   printf("Length of str: %d", len);
   return 0;
}

Output

Length of str: 14

Using Recursion

If a loop is not possible, we can use recursion to count the characters in the string:

#include <stdio.h>
int find_len(char* str) {
   if (!*str) return 0;
   return 1 + find_len(str + 1);
}
int main() {
    char str[] = "tutorialspoint";
    
    // Find length of string str
    printf("Length of str: %d", find_len(str));
    return 0;
}

Output

Length of str: 14

Using Pointer Arithmetic Trick

Increment the pointer to the string array (not the pointer to the first element of the string), then dereference it and subtract the pointer to the first character of the string.

This method can be used when the string is declared as a character array and only inside the same scope where the string is declared.
#include<stdio.h>
int main() {
   char str[] = "tutorialspoint";
   // Use pointer arithmetic to calclate
   // length of the string
   int len = *(&str + 1) - str - 1;
   printf("Length of str: %d", len);
   return 0;
}

Following is the output of the code:

Length of str: 14
Updated on: 2025-06-04T18:53:35+05:30

623 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements