This program finds string length, copy a string and compare two strings using Pointers and Functions. This is a part of Mumbai University MCA Colleges C Programs MCA Sem 1
#include<stdio.h>
#include<conio.h>
int xstrlen(char *);
void xstrcopy(char *, char *);
int xstrcomp(char *, char *);
void xstrconcat(char *);
void main()
{
char s1[20],s2[20];
int i,ch;
clrscr();
printf("\n 1.String Length \n 2.String Copy \n 3.String Compare \n 4. Concatenation of 2 Strings \n Enter your choice");
scanf("%d",&ch);
switch(ch)
{
case 1:
{
int l=0;
printf("\nEnter String");
scanf("%s",&s1);
l=xstrlen(s1);
printf("\n Length of %s is %d",s1,l);
break;
}
case 2:
{
printf("\n Enter 1st string");
scanf("%s",&s1);
printf("\n Enter 2nd string");
scanf("%s",&s2);
xstrcopy(s1,s2);
printf("\n First string: %s",s1);
break;
}
case 3:
{
int a;
printf("\n Enter 1st string");
scanf("%s",&s1);
printf("\n Enter 2nd string");
scanf("%s",&s2);
a=xstrcomp(s1,s2);
if(a==0)
printf("Strings are equal");
else
printf("Strings are not equal");
break;
}
case 4:
{
printf("\n Enter 1st string");
scanf("%s",&s1);
printf("\n Enter 2nd string");
scanf("%s",&s2);
xstrconcat(s1,s2);
printf(“String after concatenation: %s”, s1);
}
default:
{
break;
}
}
getch();
}
int xstrlen(char *s)
{
int l=0;
while(*s!='\0')
{
l++;
s++;
}
return(l);
}
void xstrcopy(char *s1, char *s2)
{
while(*s2!='\0')
{
*s1=*s2;
s1++;
s2++;
}
*s1='\0';
}
int xstrcomp(char *s1, char *s2)
{
while(*s1!='\0' && *s2!='\0')
{
if(*s1==*s2)
return(0);
s1++;
s2++;
}
return(*s1-*s2);
}
void xstrconcat(char *s1, char *s2)
{
int i=0, len=0;
while(*(s1+i)!=’\0’)
{
len++;
i++;
}
for(i=len;*s2==’\0’;++i)
{
*(s1+i)=*s2;
s2++;
}
*(s1+i)=’\0’;
}
Hope this Program is useful to you in some sense or other. Keep on following this blog for more Mumbai University MCA College Programs. Happy Programming and Studying.
No comments:
Post a Comment