pythonc++string

How to split strings in C++ like in python?


so in python you can split strings like this:

string = "Hello world!"
str1 , str2 = string.split(" ") 
print(str1);print(str2)

and it prints:

Hello 
world!

How can i do the same in C++? This wasn't useful Parse (split) a string in C++ using string delimiter (standard C++) , i need them splited so i can acces them separatedly like print just str1 for example.


Solution

  • If your tokenizer is always a white space (" ") and you might not tokenize the string with other characters (e.g. s.split(',')), you can use string stream:

    #include <iostream>
    #include <string>
    #include <sstream>
    
    int main() {
        std::string my_string = " Hello   world!  ";
        std::string str1, str2;
        std::stringstream s(my_string);
    
        s>>str1>>str2;
    
        std::cout<<str1<<std::endl;
        std::cout<<str2<<std::endl;
        return 0;
    }
    

    Keep in mind that this code is only suggested for whitespace tokens and might not be scalable if you have many tokens. Output:

    Hello
    World!