The Program in C to count the length of string inputted by user is given below:
#include <stdio.h>
#include <string.h>
int main() {
char input[1000];
printf("Enter a string: ");
fgets(input, sizeof(input), stdin);
input[strcspn(input, "\n")] = 0; // remove newline char
int length = 0;
int i = 0;
while (input[i] != '\0') {
length++;
i++;
}
printf("Length of string: %d\n", length);
return 0;
}
Output:
Enter a string: coding has become easy with codinghub
Length of string: 37
Pro-Tips💡
This program uses the fgets()
function to read a string from the keyboard, and stores it in the input
variable.
It then removes the newline character that is appended to the input by fgets
by replacing it with a null terminator.
It initializes a variable length
to 0 and uses a while loop to iterate through each character in the input string.
For each character it increases the value of the length
variable.
Finally it prints the length of the string which is stored in length
variable.
Alternatively, you can use the strlen()
function to find the length of the input string:
int length = strlen(input);
printf("Length of string: %d\n", length);
‘strlen
‘ function returns the number of characters in the input string before the null terminator. It’s faster than the while loop implementatio
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.