Tweaked .gitignore
[cluster_expansion.git] / StringTokenizer.cpp
blobf67c5ed860a16b3974ca50b1848075c129473b45
1 #include "StringTokenizer.h"
3 StringTokenizer::StringTokenizer(const std::string& _str, const std::string& _delim)
6 if ((_str.length() == 0) || (_delim.length() == 0)) return;
8 token_str = _str;
9 delim = _delim;
12 Remove sequential delimiter
14 unsigned int curr_pos = 0;
16 while(true)
18 if ((curr_pos = token_str.find(delim,curr_pos)) != std::string::npos)
20 curr_pos += delim.length();
22 while(token_str.find(delim,curr_pos) == curr_pos)
24 token_str.erase(curr_pos,delim.length());
27 else
28 break;
32 Trim leading delimiter
34 if (token_str.find(delim,0) == 0)
36 token_str.erase(0,delim.length());
40 Trim ending delimiter
42 curr_pos = 0;
43 if ((curr_pos = token_str.rfind(delim)) != std::string::npos)
45 if (curr_pos != (token_str.length() - delim.length())) return;
46 token_str.erase(token_str.length() - delim.length(),delim.length());
52 int StringTokenizer::countTokens()
55 unsigned int prev_pos = 0;
56 int num_tokens = 0;
58 if (token_str.length() > 0)
60 num_tokens = 0;
62 unsigned int curr_pos = 0;
63 while(true)
65 if ((curr_pos = token_str.find(delim,curr_pos)) != std::string::npos)
67 num_tokens++;
68 prev_pos = curr_pos;
69 curr_pos += delim.length();
71 else
72 break;
74 return ++num_tokens;
76 else
78 return 0;
84 bool StringTokenizer::hasMoreTokens()
86 return (token_str.length() > 0);
90 std::string StringTokenizer::nextToken()
93 if (token_str.length() == 0)
94 return "";
96 std::string tmp_str = "";
97 unsigned int pos = token_str.find(delim,0);
99 if (pos != std::string::npos)
101 tmp_str = token_str.substr(0,pos);
102 token_str = token_str.substr(pos+delim.length(),token_str.length()-pos);
104 else
106 tmp_str = token_str.substr(0,token_str.length());
107 token_str = "";
110 return tmp_str;
114 int StringTokenizer::nextIntToken()
116 return atoi(nextToken().c_str());
120 double StringTokenizer::nextFloatToken()
122 return atof(nextToken().c_str());
126 std::string StringTokenizer::nextToken(const std::string& delimiter)
128 if (token_str.length() == 0)
129 return "";
131 std::string tmp_str = "";
132 unsigned int pos = token_str.find(delimiter,0);
134 if (pos != std::string::npos)
136 tmp_str = token_str.substr(0,pos);
137 token_str = token_str.substr(pos + delimiter.length(),token_str.length() - pos);
139 else
141 tmp_str = token_str.substr(0,token_str.length());
142 token_str = "";
145 return tmp_str;
149 std::string StringTokenizer::remainingString()
151 return token_str;
155 std::string StringTokenizer::filterNextToken(const std::string& filterStr)
157 std::string tmp_str = nextToken();
158 unsigned int currentPos = 0;
160 while((currentPos = tmp_str.find(filterStr,currentPos)) != std::string::npos)
162 tmp_str.erase(currentPos,filterStr.length());
165 return tmp_str;