c
  1. c-program-to-find-the-length-of-a-string

Program to Find the Length of a String - (C Programs)

In this tutorial, we will discuss how to write a C program to find the length of a string.

Syntax

The syntax of the program to find the length of a string is as follows:

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

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

   printf("Enter a string: ");
   gets(str);

   length = strlen(str);

   printf("The length of the string is %d", length);

   return 0;
}

Example

Let's take an example to understand this program in detail. Suppose we have a string "Hello, World!" and we want to find its length.

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

int main()
{
   char str[100] = "Hello, World!";
   int length;

   length = strlen(str);

   printf("The length of the string is %d", length);

   return 0;
}

Output

When we compile and run the above program, we get the following output:

The length of the string is 13

Explanation

In this program, we first declare a character array str that can hold up to 100 characters. We then prompt the user to enter a string using the gets() function, which reads a line of text from the standard input (in this case, the user's keyboard).

Next, we calculate the length of the string using the strlen() function, which returns the number of characters in a string, excluding the null terminator. We then print the length of the string on the screen using the printf() function.

Use

The program to find the length of a string is used to determine the number of characters in a given string. This is often used as a basic string manipulation task in larger programs.

Summary

In this tutorial, we discussed how to write a C program to find the length of a string. We covered the syntax, example, explanation, use, and summary of the program. By using this program, you can easily find the length of any string in your C programs.

Published on: