How to split a string into different parts at each period

Hello. So, suppose I had a string, "Hello.World" and I wanted
to get from that, "Hello" and "World". How can I do this easily?
I'd consider using the C library string function strok, parse the string into tokens.
https://en.cppreference.com/w/c/string/byte/strtok
Last edited on
It's not really a Windows question. Just a C++ question.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>
#include <vector>

auto split(const std::string& str, const std::string& delim)
{
    std::vector<std::string> v;
    for (std::size_t last_pos = 0; last_pos < str.size(); )
    {
        std::size_t pos = str.find(delim, last_pos);
        if (pos == str.npos) pos = str.size();
        v.push_back(str.substr(last_pos, pos - last_pos));
        last_pos = pos + delim.size();
    }
    return v;
}

int main()
{
    std::string str {"one.two.three.four.five"};
    auto v {split(str, ".")};
    for (const auto& s: v) std::cout << s << '\n';
}

Nice C++ solution there, dutch, using std::string and C++ functions.
If the delim is a single character, then consider:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>
#include <vector>
#include <sstream>

auto split(const std::string& str, char delim)
{
	std::istringstream iss(str);
	std::vector<std::string> vs;

	for (std::string s; std::getline(iss, s, delim); vs.push_back(std::move(s)));

	return vs;
}

int main()
{
	const std::string str {"one.two.three.four.five"};
	const auto v {split(str, '.')};

	for (const auto& s : v)
		std::cout << s << '\n';
}

Last edited on
Registered users can post here. Sign in or register to post.