C Program to find the length of a string without using strlen()
|In this C Programming example, we will implement the program to find the length of a string without using strlen() and print the output on the console.
1. Length of String
The length of a string can be calculated by iterating over the characters one by one until the loop reaches the end of the string and encounters a null value “\0“.
Example Input: Hello World Output: Length of the string: 11
Helpful topics to understand this program better are-
2. C Program to find the length of a string without using strlen()
Let’s discuss the execution(kind of pseudocode) for the programto find length of a string without using strlen() in C.
- Initially, the program will prompt the user to enter the string.
- Here
fgets(input, 100, stdin)
reads the string entered by the user and passes the string in thefor
loop. - Now, in
for(i=0; input[i] != '\0' && input[i] != '\n'; i++)
loop, the program iterates over the characters in the string until it reaches the null value'\0'
or a new line'\n'
and increments the value ofi
by 1. - When the loop ends the length of the string will be printed on the console.
Let us now implement the above execution of the program to find the length of a string without using strlen() in C.
#include <stdio.h> int main() { char input[100]; int i, length = 0; printf("Enter a string \n"); fgets(input, 100, stdin); for (i = 0; input[i] != '\0' && input[i] != '\n'; i++) { length++; } printf("Length of the string: %d", length); return 0; }
Note: In the above program we can also use a while loop and the string entered must be under the range of char[] as declared in the program.
Output Enter a string Codingeek.com Length of the string: 13
3. Conclusion
In this C Programming example, we have discussed how to find the length of a string without using strlen() in C.
Helpful Links
Please follow C Programming tutorials or the menu in the sidebar for the complete tutorial series.
Also for the example C programs please refer to C Programming Examples.
All examples are hosted on Github.
Recommended Books
An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding
Do not forget to share and Subscribe.
Happy coding!! ?