Does anyone know (or have) a function writen (or in their posetion) in C++ similar to the visual basic Split() function?
What does Split do?
No, it would be pretty difficult to write something like that in c++. I would recommend looking into the "foreach" command in perl, or this clever use of strtok:
for(char *p = strtok(Packet, " "); p; p = strtok(NULL, " "))
{
// ...
}
In that, it will run that loop once for each token in the string, much like perl's foreach.
Warning: This will modify the original string.
I wrote this just for you. ;D Shouldn't be hard to modify it to take multiple delimeters -- look at basic_string::find_first_of() if you want to do that.
#include <string>
#include <vector>
std::vector<std::string> SplitStr(const std::string& text, const std::string& delimeter)
{
size_t pos = 0;
size_t oldpos = 0;
size_t delimlen = delimeter.length();
std::vector<std::string> result;
while(pos != std::string::npos)
{
pos = text.find(delimeter, oldpos);
result.push_back(text.substr(oldpos, pos - oldpos));
oldpos = pos + delimlen;
}
return result;
}
Edit: come on iago, character arrays and strok in c++? ::)
Mine is muchm much more efficient, which tends to be a major factor in my code! :-P
Or if you only want to split on whitespace (end of line, space, tab, etc) you could use a stringstream:
#include <string>
#include <sstream>
#include <vector>
vector<string> SplitStr(const string& text)
{
stringstream stream;
vector<string> result;
string tmp;
stream << text;
while(!stream.eof())
{
stream >> tmp;
result.push_back(tmp);
}
return result;
}
That's even more eew!
lol iago
stupid c++, can't make a split() function, lazy bastards... i actually like C++ better then vb, "funner" to code..
hey iago, do you use strtok to split bnet returns? or do you have your own writen function?
To split bnet returns? What are you talking about?
I use a buffer class I wrote to process b.net packets, if that's what you mean. It can be found at http://iago.valhallalegends.com .
Quote from: Sidoh on September 26, 2003, 06:26 PM
lol iago
stupid c++, can't make a split() function, lazy bastards... i actually like C++ better then vb, "funner" to code..
hey iago, do you use strtok to split bnet returns? or do you have your own writen function?
I think you are refering to extracting strings from packet data, but why would you use strtok() to do that? The strings are null terminated.
You're still thinking in VB. Stop it. Think in C++. Don't go "This is how I'd do X in VB, what's the equivalent in C++?". Do something more like: "What facility does C++ provide that will allow me to do X?". Your code will end up being much more efficient if you change your mindset a bit.