Program to Find String Length in C

C program to find the Length of a String

Here we are going to learn to write a program to find the String Length in C. There are various ways to find the string length, that is by using the predefined function or by using different loops to do so.

String-length-in-C-image

Syntax 1:

General code to compute the String Length in C using pre-defined function.
strlen(const char *str)
  • str : it is the string whose size is to be calculated by the strlen function.

Steps to find String Length in C:

  • Step 1: Start
  • Step 2: Declare the string a.
  • Step 3: Read string from the user or predefine it according to the need.
  • Step 4: Use the syntax provided to find the string length of the string.
  • Step 5: Display the string length in the stdout console.
  • Step 6: Program end.

Working:

In these program we will learn to find the string length .

Example 1 :

A simple program where we will compute string length using pre-defined functions.

Run
#include<stdio.h>
#include<string.h>
 
int main()
{
    char st[1000];
    int i;
    printf("Enter the String: ");
    scanf("%s", st);
    printf("Length of String is %ld", strlen(st));
    return 0;
}

Input:

Enter the String: 45876

Output:

Length of String is 5

Syntax 2:

General code to compute the String Length using loop.
for (i = 0; s[i] != '\0'; ++i);

In this syntax for loop is initiated from the start of the string and the value of i is incremented by “i++” until it encounters the end of the string.

Its steps are same as that of the pre-defined function and only one step needs to be changed that is the step in which we use the syntax of the pre-defined function will be replaced with for loop syntax.

Example 2 :

Program where we will compute string length using for loop.

Run
#include<stdio.h>
#include<string.h>
int main()
{
    char st[1000];
    int i;
    printf("Enter the String: ");
    scanf("%s", st);
    for (i = 0; st[i] != '\0'; ++i);
    printf("Length of String is %d", i);
    return 0;
}

Input:

Enter the String: 457896

Output:

Length of String is 6

Example 3 :

Program where we will compute the length of a pre-defined string using while loop.

Run
#include<stdio.h>
#include<string.h>
int main() 
{
   char st1[]={"Anurag"};
   int i=0, length;
   while(st1[i] !='\0')
   {
      i++;
   }
   printf(" string length is %d",i);
   return 0;
}

Output:

string length is 6

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription