Can someone please suggest me a psuedo code to extract sub problems from an arithmetic expression:
For example,
How do I remove (8*2) and (3+2) from a given string (5 + 6(3+2) - 2(8*2) +1)

Input string will always start and end with paranthesis and the sub problems must be extracted as strings too.

string[] extract(string s1)
{
string extracted[]; 
if (s1[1]==')' )
cout<<"no expression"
return NULL

else

??????????



Return extracted[]

Recommended Answers

All 2 Replies

In your example:

(5 + 6(3+2) - 2(8*2) +1)

Moving from left-to-right, in order to find a valid parenthesized pair, you have to find any condition where a ')' is found after traversing the most recent '('

From left-to-right, anytime multiple '(' are detected, the previous '(' position should be discarded.. only keep track of the position of the most current '('

Upon detection of the first ')', you now have the position of a valid parenthesized term. The parenthesis that make this term need to be discarded as candidates from future searches.

As you loop through the equation, remember the position of each ( you see. When you see a ), extract everything between the ) and the last ( you saw. Replace these characters with SPACEs to clear out the extracted section. "Unremember" the ( location since it's no longer there. Continue through the equation until you reach the end.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.