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

有帮助吗?

解决方案 2

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,},],

其他提示

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...

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top