C Program to find length of a string

Category: C Program

Write a C program to find the length of a string. How to find the length of a string in a C language. We can use the following four methods to find the length of a string. 1. Using for loop 2. Using while loop 3. Using pointer 4. Using strlen function

1. C Program to find the length of a string using for loop

#include <stdio.h>

void main()
{
  char str[50];
  int i = 0, length = 0;

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

  for (i = 0; str[i] != '\0'; i++)
    length++;

  printf("Length of string is: %d", length);
}

2. C Program to find the length of a string using while loop

#include <stdio.h>

void main()
{
  char str[50];
  int i = 0, length = 0;

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

  while (str[length] != '\0')
    length++;

  printf("Length of string is: %d", length);
}

3. C Program to find the length of a string using pointer

#include <stdio.h>

void main()
{
  char str[50];
  char *p = str;
  int length = 0;

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

  while (*p != '\0')
  {
    length++;
    *p++;
  }

  printf("Length of string is: %d", length);
}

4. C Program to find the length of a string using strlen() function

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

void main()
{
  char str[50];
  char *p = str;
  int length = 0;

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

  length = strlen(str);

  printf("Length of string is: %d", length);
}

Output

Enter the string: procoding
Length of string is: 9

Recommended Posts