LIMA
Libre Multilingual Analyzer — C++ API
Loading...
Searching...
No Matches
split_string.h
Go to the documentation of this file.
1// Copyright 2002-2021 CEA LIST
2// SPDX-FileCopyrightText: 2022 CEA LIST <gael.de-chalendar@cea.fr>
3//
4// SPDX-License-Identifier: MIT
5
6#ifndef DEEPLIMA_INCLUDE_SPLIT_STR_H
7#define DEEPLIMA_INCLUDE_SPLIT_STR_H
8
9#include <string>
10#include <vector>
11#include <cstdlib>
12#include <stdexcept>
13#include <limits>
14
15namespace deeplima
16{
17namespace utils
18{
19
20inline std::vector<std::string> split(const std::string &str, char delim)
21{
22 size_t start;
23 size_t end = 0;
24 std::vector<std::string> parts;
25
26 while ((start = str.find_first_not_of(delim, end)) != std::string::npos)
27 {
28 end = str.find(delim, start);
29 parts.push_back(str.substr(start, end - start));
30 }
31
32 return parts;
33}
34
35inline std::vector<size_t> split_list_of_nums(const std::string &str, char delim)
36{
37 std::vector<std::string> temp = split(str, delim);
38 std::vector<size_t> res;
39 res.reserve(temp.size());
40
41 for (const std::string& s : temp)
42 {
43 char *p_end = nullptr;
44 long int t = strtol(s.c_str(), &p_end, 10);
45 if (p_end != s.data() + s.size())
46 {
47 throw std::range_error("Can't parse \"" + str + "\"");
48 }
49 if (t <= 0)
50 {
51 throw std::range_error("Can't parse \"" + str + "\": value " + std::to_string(t) + " must be > 0");
52 }
53 if (size_t(t) >= std::numeric_limits<size_t>::max())
54 {
55 throw std::range_error("Can't parse \"" + str + "\": value " + std::to_string(t) + " is too high");
56 }
57 res.push_back(size_t(t));
58 }
59
60 return res;
61}
62
63template< class InputIt, class Pred >
64inline std::string join(InputIt begin, InputIt end, Pred f)
65{
66 std::string s;
67 for (auto i = begin; i != end; ++i)
68 {
69 if (s.size() > 0)
70 {
71 s += " ";
72 }
73 s += f(*i);
74 }
75 return s;
76}
77
78} // namespace utils
79} // namespace deeplima
80
81#endif
std::vector< std::string > split(const std::string &str, char delim)
std::vector< size_t > split_list_of_nums(const std::string &str, char delim)
std::string join(InputIt begin, InputIt end, Pred f)