if i have an input which is a string, how do i copy some of the string value from the string? For example 1+5-(2*3)+9, i wan to copy (2*3) from this string, how to do that?
if i have an input which is a string, how do i copy some of the string value from the string? For example 1+5-(2*3)+9, i wan to copy (2*3) from this string, how to do that?
What I do is scan the string, using a while loop, and having two parameters (int's) to mark off the left and right parentheses.
This doesn't do any actual arithmetic - so far, it just gets the sub expression.Code:#include <stdio.h> #include <string.h> void getSub(char *str, char *sub, int, int); int main() { int i, j, n, leftpar, rightpar; char str[40]={"1+5-(2*3)+9"}; //9 char sub[40]={""}; printf("\n\n"); getSub(str, sub, leftpar, rightpar); printf("\n new string is: %s", str); //check the string printf("\n sub expression is: %s", sub); //and the sub printf("\n\n\t\t\t press enter when ready"); i = getchar(); ++i; return 0; } void getSub(char *str, char *sub, int leftpar, int rightpar) { int i; i=leftpar=rightpar=0; while(str[i] != ')' && str[i] != '\0' ) { if(str[i] == '(' ) leftpar = i; ++i; } if(i) rightpar=i; str[leftpar++]=' '; //removes the '(' from the str str[rightpar]=' '; //removes the ')' " " " memcpy(sub, (str+leftpar), rightpar-leftpar); //copies our expression into sub }
Last edited by Adak; 09-02-2010 at 04:49 AM.
adak, Don't give OP the whole code. Let them show their attempt first.
give me the whole code doesnt help me very much bayint, im just wan the idea only.
Adak, can just show me on the function how strncpy work on this by copy (2*3) onli? Cause im not really clear about the parameters n function work accurately
Hi Bayint.
The OP already has posted code on this, but it was in his earlier thread:
parentheses solver
I have offered more code help than normal, because his school/teacher has asked him to do a job that they have not prepared him for.
It's not that he doesn't know how to code up a stack, (which would be the preferred way to do this, certainly), it's that he didn't know what the devil a stack was - and yeah, I put a large responsibility for that, on the school/teacher.
I know what you mean, however. It's always possible I'm being "played" by a slacker, and his cross posting is a concern in that regard.