Open In App

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

Last Updated : 05 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

C
#include <stdio.h>

int findLen(char* s) {
  	int l = 0;
    
  	// Count each character from start to end
    while (s[l]) l++;
  
  	return l;
}

int main() {
    char s[] = "Geeks";
    
    printf("%d", findLen(s));
    return 0;
}

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.

C++
#include <stdio.h>

int findLen(char* s) {
  	if (!*s) return 0;
  
  	// Add the current character to the count
  	// and find length of rest of the string
  	return 1 + findLen(s + 1);
}

int main() {
    char s[] = "Geeks";
    
  	// Find length of string s
    printf("%d", findLen(s));
    return 0;
}

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.

C
#include <stdio.h>

int main() {
    char s[] = "Geeks";

    // Calculate the length of the string using
  	// pointer arithmetic
    int l = *(&s + 1) - s - 1;

    printf("%d", l);
    return 0;
}

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.

C
#include <stdio.h>

int findLen(char* s) {
  	char* last = s;
  
	// Go to the last character
  	while(*last++);
  	
  	// Return difference between last and s
  	return last - s - 1;
}

int main() {
    char s[] = "Geeks";

    // Print the length of string s
    printf("%d", findLen(s));
    return 0;
}

Output
5

Next Article

Similar Reads