C Programming Coding String length Strings

String length

String length - C Programming - consider the string "c programming" it's length is 13. Null character is not counted when calculating string length.

This program prints length of string, for example consider the string “c programming” it’s length is 13. Null character is not counted when calculating string length. To find length of string we use strlen function of string.h.

C program to find string length

#include <stdio.h>
#include <string.h>
 
int main()
{
   char a[100];
   int length;
 
   printf("Enter a string to calculate it's length\n");
   gets(a);
 
   length = strlen(a);
 
   printf("Length of entered string is = %d\n",length);
 
   return 0;
}

 

C program to find string length without strlen

You can also find length of string without strlen function. We create our own function to find length of string.

#include <stdio.h>
 
int string_length(char []);
 
int main()
{
   char s[1000];
   int length;
 
   printf("Input a string\n");
   gets(s);
 
   length = string_length(s);
 
   printf("Length of \"%s\" = %d\n", s, length);
 
   return 0;
}
 
int string_length(char s[]) {
   int c = 0;
 
   while (s[c] != '\0')
      c++;
 
   return c;
}

Function to find string length using pointers

int string_length(char *s) {
   int c = 0;
 
   while(*(s+c))
      c++;
 
   return c;
}
READ  Shortest Paths - C/C++ - Dijkstra’s shortest path algorithm

About the author

Venkatesan Prabu

Venkatesan Prabu

Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I'm a frequent speaker at tech conferences and events.

Add Comment

Click here to post a comment