Open In App

Length of a String without Using the strlen Function in C

Last Updated : 05 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

A string in C is an array that stores a sequence of characters terminated by a NULL character. In this article, we will learn how to calculate the length of a string without using the inbuilt strlen method in C.

For Example,

Input: str= "Hello, world!"

Output: Length of string is 13

Find the Length of String without strlen in C

To find the length of a string, we generally use the strlen() function provided in the <string.h> header. But we can also find the length of the string simply by using a loop to iterate through a given string and keep counting the characters until the null terminator(‘\0’) is encountered.

Note: The NULL character ‘\0’ is not counted in the string length.

C Program to Find Length of String without strlen Function

C




// C Program to Calculate the Length of a String without
// strlen function
#include <stdio.h>
  
// Function to calculate the length of a string
int string_length(char* str)
{
    int len = 0;
  
    // Iterate through the string until the null terminator
    // is reached
    while (*str != '\0') {
        len++;
        str++;
    }
  
    return len;
}
  
int main()
{
    // Declare and initialize a character array
    char str[] = "Hello, world!";
    int length;
  
    // Calculate the length of the string using the function
    length = string_length(str);
  
    // Print the length of the string
    printf("The length of the string is: %d", length);
  
    return 0;
}


Output

The length of the string is: 13

Time Complexity: O(N), where N is the number of character in the string excluding NULL character.
Auxiliary Space: O(1)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads