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 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;
} |
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)