Thursday, August 5, 2010

C programs on character type array using string functions


There are several string manipulating functions supported by C Programing Language. These functions are available in string.h header file. One of such function is int strlen(char ch[]). This function takes a character array as argument and returns the length of the string. Length of a string means the total number of characters in the character array including blanks.

Here is an program on C Language to demonstrate the above feature

#include< stdio.h >
#include< string.h >
void main()
{
 char ch[20];
 int i;
 puts("Enter your name:-");
 gets(ch);
 i=strlen(ch);
 printf("Your name contains %d characters including space.",i);
 getch();
 }


In the above C program, the user may have entered his/her name with surname and at the end may have put a full stop. So the above program will show the length of the string including the space and the full stop. But actually the length means the total number of characters excluding the space and full stop. Our next C program on string will be a modified version of the above program that will display the number of characters in the name of the user.

C program to calculate length of a string without using library function

#include< stdio.h >
void main()
{
 char ch[20];
 int i=0,length=0;
 clrscr();
 puts("Enter your name:-");
 gets(ch);
 while(ch[i]!='\0')
 {
 if((ch[i]!=' ')&&(ch[i]!='.'))
 length++;
 i++;
 }
 printf("Your name contains %d characters .",length);
 getch();
 }

Note that in this above program string.hheader file is not used to calculate the length of the string.

1 comment:

  1. i want to fill the x position with adjacent element in the array shown below

    1X0X01
    and output should be

    100001

    ReplyDelete

Subscribe via email

Enter your email address:

Delivered by FeedBurner