13

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.

9
  • 2
    Does this answer your question? C++ split string to vector<string> Commented Jul 15, 2021 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. Commented Jul 15, 2021 at 15:55
  • I need it to return 2 strings not 2 vectors. Is there a more simple way of doing this? Commented Jul 15, 2021 at 15:59
  • 6
    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. Commented Jul 15, 2021 at 16:05
  • 3
    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 Commented Jul 15, 2021 at 16:11

5 Answers 5

11

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!
Sign up to request clarification or add additional context in comments.

5 Comments

@Bathsheba edited to use std::string only
Much better, thank you. Downvote converted to upvote. So much preferable to a wad of fiddly splitting code.
Maybe strtok as a more general answer?!
@IMAN4K: strtok may well form a more general answer but I like the specificity of this answer plus the fact that strtok is a scaled-down version of the devil.
There is NO stringstream header. It should be sstream.
2

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;
}

1 Comment

this isnt wrong, but if this is what op wants then there are already duplicate questions and answers here: stackoverflow.com/questions/43751221/… and elsewhere
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

Comments

0

Here is my implementation for std::string_view (no need to make allocations and copy memory)

std::vector<std::string_view> splitString(const char* str, char delimiter)
{
    const char* begin = str;
    const char* cur = str;
    std::vector<std::string_view> result;

    for (; *cur; ++cur)
    {
        if (*cur == delimiter)
        {
            if (cur > begin)
            {
                result.emplace_back(std::string_view(begin, cur));
            }
            begin = cur + 1;
        }
    }

    if (cur > begin)
    {
        result.emplace_back(std::string_view(begin, cur));
    }

    return result;
}

Note: before C++20 use

result.emplace_back(std::string_view(begin, static_cast<size_t>(std::distance(begin, cur))));

Comments

-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 "+" .

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.