Length of a String without Using the strlen Function in C
Last Updated :
05 Feb, 2024
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
#include <stdio.h>
int string_length( char * str)
{
int len = 0;
while (*str != '\0' ) {
len++;
str++;
}
return len;
}
int main()
{
char str[] = "Hello, world!" ;
int length;
length = string_length(str);
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)
Share your thoughts in the comments
Please Login to comment...