Вопрос

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