Open In App

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

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

C language provides the library for common string operations including string length. Otherwise, a loop can be used to count string length. But is there other ways to find the string length in C apart from above two methods. In this article, we will learn how to find length of a string without string.h and loop in C.

The most straightforward method to find length of a string without string.h and loop is by using sprintf() method. Let’s take a look at an example:

C
#include <stdio.h>


int main() {
    char s[] = "Geeks";
  
  	// Temporary buffer
  	char buff[50];
  
  	// Finding length of string s
    int l = sprintf(buff, "%s", s);
  
    printf("%d", l);
    return 0;
}

Output
5

Explanation: The sprintf() method returns the number of characters it printed in the string buffer. We could have used the printf() method too but it will output the string in the console.

There are a few more methods to find length of a string without string.h and loop in C. Some of them are:

Using Recursion

If loops cannot be used, recursion is the technique that can be used to count the number of characters in the string.

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.



Article Tags :

Similar Reads