Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Calculating the Length of the String without using the strlen() Function in C

Last Updated on August 18, 2023 by Mayank Dham

Strings are a fundamental aspect of programming, serving as containers for sequences of characters that form the backbone of text-based data manipulation. In the C programming language, the strlen() function is the go-to tool for determining the length of a string. However, there are situations where you might want to avoid using built-in library functions due to performance constraints or the desire for a deeper understanding of the underlying mechanisms. This article embarks on a journey to explore alternative methods to calculate the length of a string in C without using the strlen() function. Whether you’re aiming to optimize code, strengthen your programming skills, or enhance your understanding of C’s low-level operations, this guide provides insights into multiple strategies.

Methods to Find the Length of a String without using the strlen() Function

There are four main approaches to resolving this issue.

  • Method 1: The Standard Method
  • Method 2: Making Use of Pointers
  • Method 3: Using Bottom-Up Recursion
  • Method 4: Using Top-Down Recursion

Method 1: Standard Method

  1. Create a variable str, i, length.
  2. Printf and scanf are used to accept the value.
  3. Start a for loop.
  4. When null (‘0’), the loop should be terminated.
  5. Print the length

Code Implementation To Find the length of string in C without strlen

#include <stdio.h>
int main()
{
    char str[100];
    int i,length=0;
    
    printf("Enter a string: \n");
    scanf("%s",str);
    for(i=0; str[i]!='\0'; i++)
    {
        length++; 
    }
    
    printf("\nLength of input string: %d",length);
     return 0;
}

Output:

Enter a string: 
PREPBYTES
Length of input string: 9

Method 2: To Find the length of string in C without strlen Using Pointers

  1. Set the variables str, i, and length to their default values.
  2. Printf and scanf are used to accept the value.
  3. Call the length_of_string function, passing str as a parameter. store this in length. During the function loop, the string is traversed.
  4. When null (‘0’), the loop should be terminated.
  5. Print length.

Code Implementation o To Find the length of string in C without strlen

#include <stdio.h> 
int length_of_string(char* p) {
    int count = 0;

    while (*p != '\0') {
        count++;
        p++;
    }

    return count;
}
int main() {
    char str[100];
    int length;

    printf("Enter any string : ");
    gets(str);
    length = length_of_string(str);

    printf("The length of the given string : %d", length);

    return 0;
}

Output:

Enter a string: PREPBYTES
Length of input string: 9 

Method 3: To Find the length of string in C without strlen Using Bottom-Up Recursion

  1. Begin the main function.
  2. Create a character array str and fill it with a string.
  3. Create two integer variables, i and length, and set length to zero.
  4. The recursive function getLen(str, 0) returns the result.
  5. Return 0 to indicate that the program was successfully executed.
  6. Create a recursive function called getLen(str, len).
  7. Return the length of the string len if the current character is the null terminator ‘0’.
  8. Otherwise, increment len by one for the current character and call getLen recursively for the remainder of the string beginning with the next character.
  9. Return the string’s total length.

Code Implementation To Find the length of string in C without strlen

#include <stdio.h>
int getLen(char* str, int len)   
{
    if (*str == '\0')
        return len;
        return getLen(str + 1, len + 1);
}
int main()
{
    char str[] = "PREPBYTES";
    int i, length = 0;
    
    printf("Len: %d",getLen(str, 0));
    return 0;
}

Output:

Len: 9  

Method 4: To Find the length of string in C without strlen Using Top-Down Recursion

  1. Begin the main function.
  2. Create a character array str and fill it with a string.
  3. Create two integer variables, i and length, and set length to zero.
  4. The recursive function getLen(str) returns the result.
  5. Return 0 to indicate that the program was successfully executed.
  6. Create a recursive function called getLen(str).
  7. If the current character is the null terminator ‘0,’ return 0 to indicate that the string has come to an end.
  8. Otherwise, increment the length counter for the current character by one and call getLen recursively for the remainder of the string beginning with the next character.
  9. The final length of the string is returned.

Code Implementation To Find the length of string in C without strlen

#include <stdio.h>
int getLen(char str[])   
{
    if (str[0] == '\0')
        return 0;
    return 1 + getLen(str + 1);
}
int main()
{
    char str[] = "PREPBYTES";
    int i, length = 0;
    
    printf("Len: %d",getLen(str));
    return 0;
}

Output:

Len: 9

Conclusion
Navigating the intricacies of string manipulation in C extends beyond the standard library functions. By exploring alternative methods to determine string length without strlen() function , we’ve not only delved into the core mechanics of strings but also gained a deeper appreciation for low-level programming techniques. Whether it’s for optimizing code, enhancing your programming skills, or understanding the inner workings of strings, the approaches outlined in this article offer valuable insights into C’s fundamental operations.

Frequently Asked Questions (FAQs)

Q1. How can the length of a string be determined without the use of a function?
Ans. To find out how long a string is, convert it to a character array and count the number of elements in the array.

Q2. In C, how do I calculate the length of a string?
Ans. The built-in library function strlen() in string can be used to determine the length of a string.

Q3. In C, what is the equivalent function to strlen()?
Ans. You can either do it yourself or use the strlen() method. However, because you have tagged your question with C++, you should use a std::string instead, and then use the length (or, equivalently, size) method.

Q4. In C, how do I determine the length of a char array without using strlen()?
Ans. Making use of the sizeof() operator and pointer arithmetic.

In C, how do you calculate string length using a while loop?
while (str1[count]!= "0" Count is used to iterate through the elements in the str1 array. To determine the length of str1, you increment the count in the while loop until you reach the null character that indicates the end of the string.

Leave a Reply

Your email address will not be published. Required fields are marked *