C Program To Find Length Of A String

In this tutorial, i am going to show you how to write a program to find a length of a string using for loop, function, recursion, and built-in method in c.

All C Programs To Find Length Of A String

  • C Program To Find Length Of A String using For Loop
  • C Program To Find Length Of A String using Function
  • C Program To Find Length Of A String using Recursion
  • C Program To Find Length Of A String using strlen() function

C Program To Find Length Of A String using For Loop

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

The result of the above c program; as follows:

Enter any string: programming
Length of 'programming'= 11

C Program To Find Length Of A String using Function

int stringlength(char *s)
{
	int i;
    for(i=0; s[i]!='\0'; i++);
    return i;
	
}
int main()
{
    char s[1000];  
    int length;
 
    printf("Enter any string: ");
    gets(s);
    length=stringlength(s);
    printf("Length of '%s' = %d",s,length);
 
    return 0;
}

The result of the above c program; as follows:

Enter any string: hello
Length of 'hello' = 5

C Program To Find Length Of A String using Recursion

int stringlength(char *s,int i)
{
    if(s[i]=='\0')
     return i;
    stringlength(s,++i);
	
}
int main()
{
    char s[1000];  
    int length;
 
    printf("Enter any string: ");
    gets(s);
    length=stringlength(s,0);
    printf("Length of '%s'= %d",s,length);
 
    return 0;
}

The result of the above c program; as follows:

Enter any string: using recursion
Length of 'using recursion'= 15

C Program To Find Length Of A String using strlen() function

#include <string.h>
 
 
int main()
{
    char s[1000];  
    int length;
 
    printf("Enter any string: ");
    gets(s);
    length=strlen(s);
    printf("Length of '%s'= %d",s,length);
 
    return 0;
}

The result of the above c program; as follows:

Enter any string: hello
Length of 'hello' = 5

More C Programming Tutorials

Be First to Comment

Leave a Reply

Your email address will not be published.