Example:
Input string: I love programming. I love CodeforWin.
Output length of string: 38
Required knowledge
Basic C programming, If else, Loop, StringLogic to find length of a string
In C there is a general concept that every string must terminate with a special character that is NULL character which is also escaped as \0. Hence we use a this basic concept to find length of string. What we need to do is traverse entire string character-by-character till a NULL \0 character is found and in each iteration increment the counter value.Program to find length of string
/**
* C program to find length of a string without using library function strlen()
*/
#include <stdio.h>
int main()
{
char text[100]; /* Declares a string of size 100 */
int index= 0;
printf("Enter any string: ");
gets(text);
while(text[index]!='\0')
{
index++;
}
printf("Length of '%s' = %d", text, index);
return 0;
}
Note: You can also use pre defined library function strlen() to find length of string. strlen() is a string library function defined in string.h header file. It returns length of the string.
Program to find length of string using strlen()
/**
* C program to find length of a string using strlen() function
*/
#include <stdio.h>
#include <string.h>
int main()
{
char text[100]; /* Declares a string of size 100 */
int length;
printf("Enter any string: ");
gets(text);
length = strlen(text);
printf("Length of '%s' = %d", text, length);
return 0;
}
Output
Enter any string: I love programming. I love CodeforWin.
Length of 'I love programming. I love CodeforWin.' = 38
Length of 'I love programming. I love CodeforWin.' = 38
Happy coding ;)
You may also like
- String programming exercises index.
- C program to copy one string to another string.
- C program to concatenate two strings.
- C program to compare two strings.
- C program to convert uppercase string to lowercase string.
- C program to convert lowercase string to uppercase string
- C program to find reverse of a given string.
- C program to check whether a string is palindrome or not.
- C program to count number of vowels and consonants in a string.
- C program to find total number of words in a string.
- C program to search occurrences of a character in given string.