C Program to Find the Length of a String
In this article, you’ll learn to find the length of a string without using strlen() function.
You can use the standard library function strlen() to find the length of a string but, this program computes the length of a string manually without using strlen() function.
Example: Calculate the Length of String without Using strlen() Function
#include <stdio.h>
int main()
{
char s[1000];
int i;
printf("Enter a string: ");
scanf("%s", s);
for(i = 0; s[i] != '\0'; ++i);
printf("Length of string: %d", i);
return 0;
}
Output
Enter a string: Program Length of string: 7
C program to find the length of a string:
#include <stdio.h>
int main() {
char str[100];
int length = 0, i;
printf("Enter a string:\n");
gets(str);
for (i = 0; str[i] != '\0'; i++) {
length++;
}
printf("Length of the string: %d\n", length);
return 0;
}
Explanation:
#include <stdio.h>
includes the standard input-output header file in our program.char str[100];
declares a character arraystr
to store the input string.int length = 0, i;
declares an integer variablelength
and a loop variablei
.- The
printf()
the statement is used to display a message to the user to input a string and thegets()
the function is used to input the string. - The
for
the loop starting fromfor (i = 0; str[i] != '\0'; i++)
counting the number of characters in the stringstr
until the end of the string is reached. - The last
printf()
the statement displays the length of the string.
When we compile and run this program, it will prompt the user to input a string and then find its length. Finally, it will display the length of the string.