C program to find length of a string

Write a C program to find length of a string using loop. How to find length of a string without using in-built library function strlen() in C programming. C program to find length of string through inbuilt strlen() string function.

Example:
Input string: I love programming. I love CodeforWin.
Output length of string: 38

Required knowledge

Basic C programming, If else, Loop, String

Logic 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

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment