Search code examples
c++cstringsplitvisual-c++-2012

how to split a C++ string to get whole string individually and some parts/characters of it


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


Solution

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