MVE - Multi-View Environment mve-devel
Loading...
Searching...
No Matches
tokenizer.h
Go to the documentation of this file.
1/*
2 * Copyright (C) 2015, Simon Fuhrmann
3 * TU Darmstadt - Graphics, Capture and Massively Parallel Computing
4 * All rights reserved.
5 *
6 * This software may be modified and distributed under the terms
7 * of the BSD 3-Clause license. See the LICENSE.txt file for details.
8 */
9
10#ifndef UTIL_TOKENIZE_HEADER
11#define UTIL_TOKENIZE_HEADER
12
13#include <vector>
14#include <string>
15#include <sstream>
16#include <algorithm>
17
18#include "util/strings.h"
19#include "util/defines.h"
20
22
28class Tokenizer : public std::vector<std::string>
29{
30public:
35 void split (std::string const& str, char delim = ' ',
36 bool keep_empty = false);
37
43 void parse_cmd (std::string const& str);
44
50 std::string concat (std::size_t pos, std::size_t num = 0) const;
51
55 template <typename T>
56 T get_as (std::size_t pos) const;
57};
58
59/* ---------------------------------------------------------------- */
60
61inline void
62Tokenizer::split (std::string const& str, char delim, bool keep_empty)
63{
64 this->clear();
65 std::size_t new_tok = 0;
66 std::size_t cur_pos = 0;
67 for (; cur_pos < str.size(); ++cur_pos)
68 if (str[cur_pos] == delim)
69 {
70 std::string token = str.substr(new_tok, cur_pos - new_tok);
71 if (keep_empty || !token.empty())
72 this->push_back(token);
73 new_tok = cur_pos + 1;
74 }
75
76 if (keep_empty || new_tok < str.size())
77 this->push_back(str.substr(new_tok));
78}
79
80/* ---------------------------------------------------------------- */
81
82inline void
83Tokenizer::parse_cmd (std::string const& str)
84{
85 this->clear();
86 bool in_quote = false;
87 std::string token;
88 for (std::size_t i = 0; i < str.size(); ++i)
89 {
90 char chr = str[i];
91
92 if (chr == ' ' && !in_quote)
93 {
94 this->push_back(token);
95 token.clear();
96 }
97 else if (chr == '"')
98 in_quote = !in_quote;
99 else
100 token.push_back(chr);
101 }
102 this->push_back(token);
103}
104
105/* ---------------------------------------------------------------- */
106
107inline std::string
108Tokenizer::concat (std::size_t pos, std::size_t num) const
109{
110 std::stringstream ss;
111 std::size_t max = (num == 0
112 ? this->size()
113 : std::min(pos + num, this->size()));
114
115 for (std::size_t i = pos; i < max; ++i)
116 {
117 ss << (i == pos ? "" : " ");
118 ss << this->at(i);
119 }
120
121 return ss.str();
122}
123
124/* ---------------------------------------------------------------- */
125
126template <typename T>
127inline T
128Tokenizer::get_as (std::size_t pos) const
129{
130 return string::convert<T>(this->at(pos));
131}
132
134
135#endif /* UTIL_TOKENIZE_HEADER */
Simple tokenizer.
Definition tokenizer.h:29
#define UTIL_NAMESPACE_BEGIN
Definition defines.h:13
#define UTIL_NAMESPACE_END
Definition defines.h:14