StringTokenizer

C++

Public Domain

A simple C++ implementation of Java's StringTokenizer

Download (right click, save as, rename as appropriate)

Embed

 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
#ifndef STRING_TOKENIZER_H
#define STRING_TOKENIZER_H

#include <string>

class StringTokenizer{
	std::string s;
	std::string d;
	size_t pos;
	void SkipToNextNonDelimiter(){
		while(pos < s.size()){
			if(d.find(s[pos]) != std::string::npos){ // if is a delimiter
				pos++;
			}else{
				break;
			}
		}
	}
public:
	StringTokenizer(const std::string &str, const char *delimiters = " \t\n\r"):
	s(str),
	d(delimiters),
	pos(0)
	{
		SkipToNextNonDelimiter();
	}
	~StringTokenizer(){}

	bool hasNext() const{
		return pos < s.size();
	}

	void next(std::string &str){
		int newpos = pos+1;
		while(newpos < s.size()){
			if(d.find(s[newpos]) == std::string::npos){ // if NOT a delimiter
				newpos++;
			}else{
				break;
			}
		}
		str = s.substr(pos, newpos-pos);
		pos = newpos;
		SkipToNextNonDelimiter();
		//std::cout << pos << std::endl;
	}
};


#endif