Splitting a string

Hello again everyone!

I have another question: is there any way to split a string?

string = "C:\\Program Files\\Projects\\C++\\Folder\\"

I want to know if there is any way to split this into something like:

str1 = "C:"
str2 = "Program Files"
str3 = "Projects"
str4 = ...

Thank you!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <string>
#include <vector>
#include <sstream>

std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems)
{
    std::stringstream ss(s);
    std::string item;
    while(std::getline(ss, item, delim))
    {
        elems.push_back(item);
    }
    return elems;
}


std::vector<std::string> split(const std::string &s, char delim)
{
    std::vector<std::string> elems;
    return split(s, delim, elems);
}

int main()
{
    using namespace std;
    string sentence = "C:\\Program Files\\Projects\\C++\\Folder\\";
    std::vector<std::string> x = split(sentence, '\\');
    for (int i = 0; i < x.size(); i++)
    {
        cout << x[i] << "\n";
    }

    return 0;
}
this code adds those smaller strings into separate variables? (str1,str2,str3,...)
This code adds the smaller strings into a std::vector. You can extract them later into separate variables from it if you really need/want.
Thank you very much
Ok, i'm back again. I've been searching how to extract elements from a vector but i didn't find anything useful.

Can you please tell me how can it be done?
Last edited on
Lines 29 to 32 should give you some sort of idea.
Thank you very much, I should have spent more time inspecting this code.

Thanks again!
Topic archived. No new replies allowed.