PROGRAM - 12
a) Write a program to display the position or index in the main string S where the sub-string T begins. Display -1 if S does not contain T.
Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char s[50],t[10],*pos;
int posn;
clrscr();
printf("enter the main string");
gets(s);
printf("enter the sub string");
gets(t);
pos=strstr(s,t);
if(pos)
posn=pos-s+1;
else
posn=-1;
printf("the position of the sub string is %d"
,posn);
getch();
}
/*
INPUT:enter the main string VIVEKANANDA
enter the sub string NANDA
OUTPUT:
the position of the sub string is 7
*/
b) Write a program to count the number of lines,
words and characters in a given text.
Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
int ch,l=0,w=0,c=0,end=0,line[50],i,chrctr=0;
clrscr();
printf("Enter the text and press enter twice \n");
while(end==0)
{
c=0;
while((ch=getchar())!='\n')
{
line[c++]=ch;
chrctr++;
}
line[c]='\0';
if(line[0]=='\0')
break;
else
{
w++;
for(i=0;line[i]!='\0';i++)
{
if(line[i]==' '||line[i]=='\t')
w++;
if(line[i]==' '&&line[i+1]=='\0')
w--;
}
}
l=l+1;
}
printf("the text contains\n");
printf("%4d lines\n%4d words\n%4d characters"
,l,w,chrctr);
getch();
}
/*
INPUT:Enter the text and press enter twice
OUTPUT:
THINK POSITIVE BE AN OPTIMIST
KNOWLEDGE IS DIVINE
the text contains
2 lines
8 words
48 characters
*/
No comments:
Post a Comment