C - Programs to Implement String Operations
- Using Pointers
(1) Reversing a string
(2) Palindrome
(3) Copy
(4) String comparison
(5) Searching a string(substring)
*/
#include <stdio.h>
#include<conio.h>
#include<ctype.h>
#include<stdlib.h>
/*function prototypes*/
void reverse(char *a);
int palindrome(char *a);
void copy(char *b,char *a);
int compare(char *a,char *b);
void search(char *a,char *b);
void main()
//main function starts
{ char a[100],b[100];
int result,op;
clrscr();
do
//do while loop starts
{ /* display the menu */
printf("\n1)Reverse the Given String");
printf("\n2)Check for palindrome");
printf("\n3)Copy");
printf("\n4)String Comparison");
printf("\n5)String Searching(substring)");
printf("\n6)Quit");
printf("\n\nEnter Your Choice:");
scanf("%d",&op);
flushall();
switch(op) //switch case starts
{
case 1: printf("\n Enter a String:");
gets(a);
reverse(a); //call to reverse
printf("\n Result=%s",a);
printf("\n\n press a Character !!!!!!");
getch();
break;
case 2: printf("\n Enter a String:");
gets(a);
result=palindrome(a); //call to palindrome
if(result==0)
printf("\nNot a palindrome");
else
printf("\nA palindrome");
printf("\n\n press a Character !!!!!!");
getch();
break;
case 3: printf("\n Enter a String:");
gets(a);
copy(b,a); //call to copy
printf("\nResult=%s",b);
printf("\n\n press a Character !!!!!!");
getch();
break;
case 4: printf("\n Enter 1st string:");
gets(a);
printf("\n Enter 2nd string:");
gets(b);
result=compare(a,b); //call to compare
if(result==0)
printf("\nboth are same");
else
if(result>0)
printf("\n1st>2nd");
else
printf("\n1st<2nd");
printf("\n\n press a Character !!!!!!");
getch();
break;
case 5: printf("\n Enter 1st string:");
gets(a);
printf("\n Enter 2nd string:");
gets(b);
search(a,b); //call to search
printf("\n\n press a Character !!!!!!");
getch();
break;
}
}while(op!=6);
}
void reverse(char *a)
{ char *p,*q;
char temp;
p=q=a;
while(*q!='\0')
q++;
/* q is on the null character*/
q--;
while(p<q)
{ temp=*p; *p=*q;*q=temp;
p++;q--;
}
}
int palindrome(char *a)
{ char *p,*q;
p=q=a;
while(*q!='\0')
q++;
/* q is on the null character*/
q--;/*q is on the last character*/
while(p<q)
{ if(*p!=*q)
return(0);
p++;q--;
}
return(1);
}
void copy(char *b,char *a)
{ while(*a!='\0')
{ *b=*a;
a++;b++;
}
*b='\0';
}
int compare(char *a,char *b)
{
while(*a!='\0')
{
if(*a > *b)
return(1);
if(*a < *b)
return(-1);
a++;b++;
}
return(0);
}
void search(char *a ,char *b)
{ int lena,lenb;
char *i,*j,*k;
for(lena=0;*(a+lena)!='\0';lena++)
;
for(lenb=0;*(b+lenb)!='\0';lenb++)
;
/* searching */
for(i=a;i<=a+lena-lenb+1;i++)
{ k=i;
for(j=b;*k==*j&& *j!='\0';j++,k++)
;
if(*j=='\0')
printf("\nstring found at location:%d",i-a+1);
}
}