C program to find the Length of String
The total number of characters in a string is called as length of that string.
There are two ways of finding the length of a string:
- By counting the individual characters of string without using built in library function.
- Using strlen() function – it is a built in library function.
Example 1: Program to find the length of string without using Library function
Let us write a c program to count the characters of a string without using strlen() function. It is easy to find the length of string using while loop.Description:
s – input string. It is an array.c – variable to count the characters.
‘\0’ – NULL character. It marks the end of string.
Algorithm to find the length of string:
STEP 1: START
STEP 2: SET the value of count
count = 0
STEP 3: READ the input string whose length is to be counted
READ s
STEP 4: REPEAT until end of string is not reached
LOOP character != NULL
INCREMENT the character count
count = count + 1
STEP 5: PRINT the length of string
PRINT “count”
STEP 6: END
STEP 2: SET the value of count
count = 0
STEP 3: READ the input string whose length is to be counted
READ s
STEP 4: REPEAT until end of string is not reached
LOOP character != NULL
INCREMENT the character count
count = count + 1
STEP 5: PRINT the length of string
PRINT “count”
STEP 6: END
Program to find the length of string with out using built in function:
#include<stdio.h>#include<conio.h>
int main()
{
char s[1000];
int count = 0;
printf("Input a string:\n");
gets(s);
while (s[count] != '\0')
count++;
printf("Length of the string: %d\n", count);
getch();
return 0;
}
Output 1:
Input a string:icantutorials
Length of the string: 13
Output 2:
Input a string:Learning
Length of the string: 8
Example 2: Program to find the length of string using strlen() function:
- strlen() is a built in library function which is present inside the header file string.h
- The strlen() function returns the length of the given string.
- It doesn’t count null character ‘\0’.
#include <string.h>
#include<conio.h>
int main()
{
char s[100];
int count;
printf("Enter a string:\n");
gets(s);
count = strlen(s);
printf("Length of the string = %d\n", count);
getch();
return 0;
}
Output:
Enter a string:success
Length of the string = 7
QUIZ:
1] strlen() function is present in header file.
- stdio.h
- conio.h
- string.h
- math.h
- \n
- \0
- \t
- \r