Search code examples
c++stringtoken

C++ Tokenize a string with spaces and quotes


I would like to write something in C++ that tokenize a string. For the sake of clarity, consider the following string:

add string "this is a string with spaces!"

This must be split as follows:

add
string
this is a string with spaces!

Is there a quick and standard-library-based approach?


Solution

  • No library is needed. An iteration can do the task ( if it is as simple as you describe).

    string str = "add string \"this is a string with space!\"";
    
    for( size_t i=0; i<str.length(); i++){
    
        char c = str[i];
        if( c == ' ' ){
            cout << endl;
        }else if(c == '\"' ){
            i++;
            while( str[i] != '\"' ){ cout << str[i]; i++; }
        }else{
            cout << c;
        }
    }
    

    that outputs

    add
    string
    this is a string with space!