Tuesday, August 23, 2011

String valid or not

#include<stdio.h>
#include<conio.h>
#define SIZE 100
struct stack
{
int top;
char items[SIZE];
};
void push(struct stack*,char);
char pop(struct stack*);
int empty(struct stack*);
void main()
{
struct stack s;
struct stack *ps;
char *str;
int valid=1;
ps=&s;
s.top=-1;
clrscr();
printf("enter a string to check its validity\n");
printf("String::");
scanf("%s",str);
printf("\nString is %s",str);
while(*str!='\0')
{
char ch;
char temp;
ch=*str;

//printf("\n character taken from string is %c",ch);

if(ch=='(' || ch=='{' || ch=='[')
push(ps,ch);
if(ch==')' || ch=='}' || ch==']')
{
if(empty(ps))
{
valid=0;
break;
}
else
{
temp=pop(ps);
if(temp=='('&& ch==')' || temp=='{'&& ch=='}' || temp=='['&& ch==']')
{
valid=1;
}
else
{valid=0;break;}
}
}
str++;
}//end while

if(!empty(ps))
valid=0;

if(valid)
printf("\nString is valid");
else
printf("\nString is not valid");

getch();
}//end main

void push(struct stack *ps,char ch)
{
ps->items[++(ps->top)]=ch;
}
char pop(struct stack *ps)
{
return(ps->items[(ps->top)--]);
}
int empty(struct stack *ps)
{
if(ps->top==-1)
return 1;
return 0;
}
output:
enter a string to check its validity
String::a+b(-2+3))
String is a+b(-2+3))
String is not valid

No comments:

Post a Comment

Feel free to comment......