Tuesday, February 22, 2011

String Lenth Program!!

The programs given below calculate the lenth of the given string. (a) is the program for calculating the length without using the built-in functions , whereas (b) uses the built-in function from the header file <string.h>


(a)
The length of the string is the number of spaces it occupies. It is calculated using the for control structure. When the sring ends the system assingns '\0' for the next space.

For example, Let us take the string 'an' , a[0]='a' ; a[1]='n' ; a[2]='\0'.
 Hence by finding the ith position in which a[i]='\0', the string length is determined.


PROGRAM:
#include<stdio.h>
#include<conio.h>
void main()
{
char a[80];
int l;
clrscr();
printf("\nEnter the String:");
gets(a);
l=sl(a);
printf("\nLength of String A is %d",l);
getch();
}

int sl(char str[])
{
int i;
  for (i=0;i<=80;i++)
   {
     if (str[i]=='\0')
     return(i);
   }
}


(b)
Using the header file 'string.h' makes our work simpler with the 'strlen' command, which calculates the spring length automatically.


PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char a[80];
int l;
clrscr();
printf("\nEnter the String:");
gets(a);
l=strlen(a);
printf("\nThe Length of %s is %d",a,l);
getch();
}



No comments:

Post a Comment