VOOZH about

URL: https://www.geeksforgeeks.org/c/length-of-string-without-using-the-strlen-function-in-c/

⇱ Length of a String Without Using strlen() Function in C - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Length of a String Without Using strlen() Function in C

Last Updated : 5 Dec, 2024

The length of a string is the number of characters in it without including the null character. C language provides the strlen() function to find the lenght of the string but in this article, we will learn how to find length of a string without using the strlen() function.

The most straightforward method to find length of a string without using the strlen() function is by using a loop to traverse the whole string while counting the number of characters. Let’s take a look at an example:


Output
5

There are also a few other methods in C to find length of a string without using the strlen() function. Some of them are as follows:

Using Recursion

The number of characters in the string can also be counted using recursion.


Output
5

Using Pointer Arithmetic Trick

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


Output
5

Note: This method can only be used when the string is declared as character array and only inside the same scope as string is declared.

Using Pointer Subtraction

Use pointer subtraction to find the difference between the pointer to the first and last character of the string, calculating the length excluding the null terminator.


Output
5
Comment