1

My question is, how can I split a string in C++? For example, I have `

string str = "[ (a*b) + {(c-d)/f} ]" 
  1. It need to get the whole expression individually like [,(,a,*,b,......
  2. And I want to get the brackets only like [,(,),{,(,),},] on their proper position

How can I do these with some easy ways

8
  • possible duplicate of Splitting a string in C++ Commented Sep 15, 2013 at 8:33
  • I doubt there is a way where you can do "both of these at once" (other than writing your own parser that does one thing for each toke, and something else for the brackets). Commented Sep 15, 2013 at 8:35
  • 1
    There are no easy ways to do this in C++. There are functions for finding strings or characters in strings, and functions for extracting substrings from strings. But you have to write the code that puts these together to do precisely what you want. Commented Sep 15, 2013 at 8:36
  • Why exactly do you ask? Is this a homework? Do you want a calculator? Commented Sep 15, 2013 at 8:54
  • No, perhaps you may have read the applications of stack; it contains 1.Verifying the brackets in an expression and 2. calculating the infix/postfix expressions. I want to implement that Commented Sep 15, 2013 at 9:09

2 Answers 2

3

This is called lexical analysis (getting tokens from some sequence or stream of characters) and should be followed by parsing. Read e.g. the first half of the Dragon Book.

Maybe LL parsing is enough for you....

There are many tools for that, see this question (I would suggest ANTLR). You probably should build some abstract syntax tree at some point.

But it might not worth the effort. Did you consider embedding some scripting language in your application, e.g. lua (see this and this...), or gnu guile, python, etc...

Sign up to request clarification or add additional context in comments.

Comments

1

Here is a way I got to do this,

string expression = "[ (a*b) + {(c-d)/f} ]" ; string token ; // appending an extra character that i'm sure will never occur in my expression // and will be used for splitting here expression.append("~") ; istringstream iss(expression); getline(iss, token, '~'); for(int i = 0 ; i < token.length() ; i++ ) { if(token[i] != ' ' ) { cout<<token[i] << ","; } } 

Output will be: [,(,a,*,b,),+,{,(,c,-,d,),/,f,},],

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.