Statistics
| Branch: | Revision:

root / src / common / stringtokenizer.cc @ master

History | View | Annotate | Download (1.97 KB)

1
//==========================================================================
2
//  STRINGTOKENIZER.CC - part of
3
//                     OMNeT++/OMNEST
4
//            Discrete System Simulation in C++
5
//
6
//
7
//  Declaration of the following classes:
8
//    StringTokenizer  : string tokenizer utility class
9
//
10
//  Author: Andras Varga
11
//
12
//==========================================================================
13

    
14
/*--------------------------------------------------------------*
15
  Copyright (C) 2006-2008 OpenSim Ltd.
16

17
  This file is distributed WITHOUT ANY WARRANTY. See the file
18
  `license' for details on this and other legal matters.
19
*--------------------------------------------------------------*/
20

    
21
#include <assert.h>
22
#include <stdlib.h>
23
#include <string.h>
24
#include "stringtokenizer.h"
25

    
26
USING_NAMESPACE
27

    
28

    
29
StringTokenizer::StringTokenizer(const char *s, const char *delim)
30
{
31
    if (!s)
32
        s = "";
33
    if (!delim || !*delim)
34
        delim = " \t\n\r\f";
35
    delimiter = delim;
36
    str = new char[strlen(s)+1];
37
    strcpy(str,s);
38
    rest = str;
39
}
40

    
41
StringTokenizer::~StringTokenizer()
42
{
43
    delete [] str;
44
}
45

    
46
void StringTokenizer::setDelimiter(const char *delim)
47
{
48
    if (!delim || !*delim)
49
        delim = " \t\n\r\f";
50
    delimiter = delim;
51
}
52

    
53
inline void skipDelimiters(char *&s, const char *delims)
54
{
55
    while (*s && strchr(delims, *s)!=NULL) s++;
56
}
57

    
58
inline void skipToken(char *&s, const char *delims)
59
{
60
    while (*s && strchr(delims, *s)==NULL) s++;
61
}
62

    
63
const char *StringTokenizer::nextToken()
64
{
65
    skipDelimiters(rest, delimiter.c_str());
66
    if (!*rest) return NULL;
67
    const char *token = rest;
68
    skipToken(rest, delimiter.c_str());
69
    if (*rest)
70
        *rest++ = '\0';
71
    return token;
72
}
73

    
74
bool StringTokenizer::hasMoreTokens()
75
{
76
    skipDelimiters(rest, delimiter.c_str());
77
    return *rest;
78
}
79

    
80
std::vector<std::string> StringTokenizer::asVector()
81
{
82
    const char *s;
83
    std::vector<std::string> v;
84
    while ((s=nextToken())!=NULL)
85
        v.push_back(std::string(s));
86
    return v;
87
}
88

    
89