Wednesday, April 30, 2025

C Program - strlen() Function Example - Find the Length of a String

This program prompts the user to enter a string and then calculates and displays the length of the entered string. The program continues to prompt the user for input until the program is terminated. 

#include <stdio.h>
#include <string.h>

int main()
{

    char some_string[100];
    int length;

    while (1)
    {
        printf("Enter String: \n");
        gets(some_string);

        length = strlen(some_string);
        printf("String Length for %s is %d: \n", some_string, length);
        printf("-------------------------------------- \n");
    }

    return 0;
}

Result: 

Enter String:
some string
String Length for some string is 11:
--------------------------------------
Enter String:
test
String Length for test is 4:
--------------------------------------
Enter String:

Here's a line-by-line explanation of the code: 

#include <stdio.h>
#include <string.h>

This program includes the standard input/output library and the string library. 

int main()
{
    char some_string[100];
    int length;

This declares a character array some_string of size 100 to store the user input and an integer length to store the length of the input string. 

    while (1)
    {
        printf("Enter String: \n");
        gets(some_string);

This is a loop that prompts the user to enter a string and reads it from the console using gets() function. gets() reads the input as a character string, which is then stored in some_string.

Note: gets() is not safe to use, as it does not check the length of the input, so it can cause a buffer overflow if the input string is larger than the size of the array. 

        length = strlen(some_string);
        printf("String Length for %s is %d: \n", some_string, length);
        printf("-------------------------------------- \n");
    }

This calculates the length of the input string using the strlen() function and stores it in the length variable. The length is then printed to the console using printf() function. 

    return 0;
}

This ends the main function and returns 0, indicating successful execution of the program.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...