How to Find String Length in C

C-String-Programs

In this article, we are going to learn how to find string length in C language. We will learn this with the help of multiple techniques

  • Find string length using loop in C language.
  • Find string length using pointer functions in C language.
  • Find string length using built in strlen() function.

Find string length using loop in C language


In this example, we are going to learn how we can calculate the length of a string with the help of a loop. We are looping over the characters of the string and also counting them so we can get the length of the string at the end of this iteration. let us see the code example.

#include <stdio.h>

int main() 
{
   char str[] = "DevEnum.com";
   int len = 0;
      
   while(str[len] != '
#include <stdio.h>

int main() 
{
   char str[] = "DevEnum.com";
   int len = 0;
      
   while(str[len] != '\0') 
  {
      len++;
   }
   
   printf("The Length of string '%s' is %d", str, len);
   
   return 0;
}
') { len++; } printf("The Length of string '%s' is %d", str, len); return 0; }

Output

The Length of string 'DevEnum.com' is 11

Find string length using pointer function in C language


In this example, we are trying to find the length of the string using the concept of the pointer. We are again iterating over the string with the help of the pointer and we are iterating until we reach the null pointer which is the end of the string. Let us understand this with the below code example.

#include <stdio.h>

int GetStringlengh(const char* s)
{
     int size = 0;

     while (*s) 
    {
         size += 1;
         s += 1;
     }

     return size;
 }

 int main() {

     char str[] = "Please Visit DevEnum.com for C Programs";

     int strlen = 0;

     strlen = GetStringlengh(str);

     printf("The length of the String is : %d", strlen);

     return 0;
 }

Output

The length of the String is : 39

Find string length using built in strlen() function


n this example, we are using the C Standard library built-in function strlen() to calculate the length of a string in C.
This function just takes
the string for which we want to calculate the length and returns the length. Let us see the code example.

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

int main() {
     char str[] = "Please Visit DevEnum.com for C Programs";

     int strln = 0;

     strln = strlen(str);

     printf("The length of the String is : %d", strln);

     return 0;
 }

Output

The length of the String is : 39