SOURCE FILE: ABCD.cpp
/*
Programmer: John Sarraille
Date: February, 2008
This is a program to check a string to see if it is an expression in the
language defined by:
<expression> = AC | AD | BC | BD
| A<expression>C
| A<expression>D
| B<expression>C
| B<expression>D
*/
#include <iostream>
#include <string>
using namespace std;
bool isExpr (string str) ;
int main ()
{
string testStr;
cout << endl << endl << "The Expression Checker is running." ;
cout << endl << endl ;
cin >> testStr ;
cout << testStr << endl;
if (isExpr(testStr))
cout << "The string IS an expression." << endl ;
else cout << "The string IS NOT an expression." << endl ;
cout << endl << endl << "The Expression Checker Thanks You!" ;
cout << endl << endl ;
return 0 ;
}
bool isExpr (string str)
{
int len = str.length() ;
return (str == "AC")
|| (str == "AD")
|| (str == "BC")
|| (str == "BD")
|| ( (len >1)
&& (str.substr(0,1) == "A")
&& (str.substr(len-1,1) == "C")
&& isExpr(str.substr(1,len-2)) )
|| ( (len >1)
&& (str.substr(0,1) == "A")
&& (str.substr(len-1,1) == "D")
&& isExpr(str.substr(1,len-2)) )
|| ( (len >1)
&& (str.substr(0,1) == "B")
&& (str.substr(len-1,1) == "C")
&& isExpr(str.substr(1,len-2)) )
|| ( (len >1)
&& (str.substr(0,1) == "B")
&& (str.substr(len-1,1) == "D")
&& isExpr(str.substr(1,len-2)) ) ;
}
/* Alternate form for the logic of isExpr:
bool isExpr (string str)
{
int len = str.length() ;
bool result ;
if (str == "AC") result = true ;
else if (str == "AD") result = true ;
else if (str == "BC") result = true ;
else if (str == "BD") result = true ;
else if ( (len >1)
&& (str.substr(0,1) == "A")
&& (str.substr(len-1,1) == "C")
&& isExpr(str.substr(1,len-2)) )
result = true ;
else if ( (len >1)
&& (str.substr(0,1) == "A")
&& (str.substr(len-1,1) == "D")
&& isExpr(str.substr(1,len-2)) )
result = true ;
else if ( (len >1)
&& (str.substr(0,1) == "B")
&& (str.substr(len-1,1) == "C")
&& isExpr(str.substr(1,len-2)) )
result = true ;
else if ( (len >1)
&& (str.substr(0,1) == "B")
&& (str.substr(len-1,1) == "D")
&& isExpr(str.substr(1,len-2)) )
result = true ;
else result = false ;
return result ;
}
*/