File: StringTokenizer.cpp

package info (click to toggle)
drbd-utils 9.5.0-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 5,388 kB
  • sloc: ansic: 43,698; xml: 15,968; cpp: 7,783; sh: 3,699; makefile: 1,353; perl: 353
file content (60 lines) | stat: -rw-r--r-- 1,332 bytes parent folder | download | duplicates (5)
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <StringTokenizer.h>

StringTokenizer::StringTokenizer(const std::string& tokens_line, const std::string& tokens_delimiter):
    line(tokens_line),
    delimiter(tokens_delimiter)
{
    length = line.length();

    find_next_token();
}

bool StringTokenizer::has_next()
{
    return have_token;
}

// @throws std::bad_alloc, std::out_of_range
std::string StringTokenizer::next()
{
    if (!have_token)
    {
        throw std::out_of_range("StringTokenizer.next() called, but no more tokens are available");
    }

    // Save current token substring parameters
    size_t cur_offset = token_offset;
    size_t cur_length = token_length;

    // Prepare next token substring parameters
    find_next_token();

    // Return current token
    return line.substr(cur_offset, cur_length);
}

void StringTokenizer::find_next_token()
{
    have_token = false;
    while (!have_token && index < length)
    {
        token_offset = index;
        index = line.find(delimiter, token_offset);
        if (index == std::string::npos)
        {
            index = length;
        }

        token_length = index - token_offset;
        if (token_length >= 1)
        {
            // Found a non-zero length token
            have_token = true;
        }

        if (index < length)
        {
            ++index;
        }
    }
}