6

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.

  • 2
    Does this answer your question? [C++ split string to vector](https://stackoverflow.com/questions/43751221/c-split-string-to-vectorstring) – zerocukor287 Jul 15 '21 at 15:54
  • Boost has a nice string splitter. If you have your heart set on using the `str1 , str2` notation you'd have to do something really clever with your own class and an overloaded expression separator operator and assignment operator. – Bathsheba Jul 15 '21 at 15:55
  • I need it to return 2 strings not 2 vectors. Is there a more simple way of doing this? –  Jul 15 '21 at 15:59
  • There is [at least one answer](https://stackoverflow.com/a/46931770/10077) in the question you linked that will give you a vector back. If you want the Python tuple unpacking, that gets trickier. C++ has [`std::tie`](https://en.cppreference.com/w/cpp/utility/tuple/tie), but I believe that works only with `std::tuple`s. And that isn't going to be easy to deal with in C++. – Fred Larson Jul 15 '21 at 15:59
  • 5
    Sometimes you have to let go of how you wrote code in language X and embrace the idioms of language Y. If it is hard to do something X's way, do it Y's way. – user4581301 Jul 15 '21 at 16:05
  • what does `split` do when there is more than one delimiter? Does it always split on the first delimiter found and returns two strings? Or can it be more return values? – 463035818_is_not_an_ai Jul 15 '21 at 16:08
  • @stacker you misunderstood comments, like in python split returns list of strings in same way `boost::split` returns vector of strings. – Marek R Jul 15 '21 at 16:09
  • Handy reading: [Structured Bindings](https://en.cppreference.com/w/cpp/language/structured_binding) – user4581301 Jul 15 '21 at 16:10
  • 2
    you should focus on the functionality you want to use not just "I want to do the same in C++". It almost never happens that two functions in different languages behave exactly the same for all input. If you want to split in two strings always this can be done in C++ as well – 463035818_is_not_an_ai Jul 15 '21 at 16:11

4 Answers4

7

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

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!
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
aminrd
  • 4,300
  • 4
  • 23
  • 45
3

You could create your own splitString function. Here is an example:

std::vector<std::string> splitString(std::string str, char splitter){
    std::vector<std::string> result;
    std::string current = ""; 
    for(int i = 0; i < str.size(); i++){
        if(str[i] == splitter){
            if(current != ""){
                result.push_back(current);
                current = "";
            } 
            continue;
        }
        current += str[i];
    }
    if(current.size() != 0)
        result.push_back(current);
    return result;
}

And here is an example usage:

int main(){ 
    vector<string> result = splitString("This is an example", ' ');
    for(int i = 0; i < result.size(); i++)
        cout << result[i] << endl;

    return 0;
}

Or how you want to use it:

int main(){
    vector<string> result = splitString("Hello world!", ' ');
    string str1 = result[0];
    string str2 = result[1];
    cout << str1 << endl;
    cout << str2 << endl;

    return 0;
}
Marko Borković
  • 1,884
  • 1
  • 7
  • 22
  • this isnt wrong, but if this is what op wants then there are already duplicate questions and answers here: https://stackoverflow.com/questions/43751221/c-split-string-to-vectorstring and elsewhere – 463035818_is_not_an_ai Jul 15 '21 at 16:15
1

Using boost:

#include <iostream>
#include <boost/algorithm/string.hpp>
#include <vector>

int main()
{
    std::string line;
    while(std::getline(std::cin, line)) {
        std::vector<std::string> v;
        boost::split(v, line, boost::is_any_of(" "));
        for (const auto& s : v) {
            std::cout << s << " - ";
        }
        std::cout << '\n';
    }
    return 0;
}

https://godbolt.org/z/EE3xTavMr

Marek R
  • 32,568
  • 6
  • 55
  • 140
1
#include<bits/stdc++.h>
using namespace std;
int main(){
    string str ="123/43+2342/23432";
    size_t found = str.find("+");
    int b=found;
    int a,c;
    size_t found1 = str.find("/");
    if(found1!=string::npos){
        a = found1;
    }
    found1 = str.find("/",found1+1);
    if(found1!=string::npos){
        c = found1;
    }
    string tmp1 = str.substr(0,a-0);
    int num1 = stoi(tmp1);
    tmp1 = str.substr(a+1,b-a-1);
    int del1 = stoi(tmp1);
    tmp1 = str.substr(b+1,c-b-1);
    int num2 = stoi(tmp1);
    tmp1 = str.substr(c+1);
    int del2 = stoi(tmp1);

    cout<<num1<<" "<<del1<<" "<<num2<<" "<<del2<<endl;
    
    return 0;
}

Split all the number given in the string when you find "/" or "+" .