How to find length of a string without string.h and loop in C?


In this section we will see how to find length of a string without using string header file and loops in C. The string length finding problem can be solved without string.h very easily. We can use recursive function to do it.

But in this example we are not using recursion. We are using another trick to do that. We are using printf() function to get the length. The printf() function returns the number of character it has printed. If we print only that string using a printf() function, we can easily get the length of it.

Example Code

#include<stdio.h>
main() {
   char* my_str = "This is a String";
   printf("The string is: ");
   int length = printf("%s", my_str);
   printf("\nThe length of string is: %d", length);
}

Output

The string is: This is a String
The length of string is: 16

Updated on: 30-Jul-2019

506 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements