Std::Vector to String with Custom Delimiter

std::vector to string with custom delimiter

Use delimiter.c_str() as the delimiter:

copy(x.begin(),x.end(), ostream_iterator<int>(s,delimiter.c_str()));

That way, you get a const char* pointing to the string, which is what ostream_operator expects from your std::string.

Spliting a string with multiple delimiter and save it into a vector

You can do this using per-character logic if you think through the states involved....

std::vector<std::string> tokens;
std::string delims = " \n()";
char c;
bool last_was_delim = true;
while (f.get(c))
if (delims.find(c) != tokens.end())
{
tokens.emplace_back(1, c);
last_was_delim = true;
}
else
{
if (last_was_delim)
tokens.emplace_back(1, c); // start new string
else
tokens.back() += c; // append to existing string
last_was_delim = false;
}

Obviously this considers say "((" or " " (two spaces) to be repeated distinct delimiters, to be entered into tokens separately. Tune to taste if necessary.

Equivalently, but using flow control instead of a bool / a different while (f.get(c)) loop handles additional characters for an in-progress token:

std::vector<std::string> tokens;
std::string delims = " \n()";
char c;
while (f.get(c))
if (delims.find(c) != tokens.end())
tokens.emplace_back(1, c);
else
{
tokens.emplace_back(1, c); // start new string
while (f.get(c))
if (delims.find(c) != tokens.end())
{
tokens.emplace_back(1, c);
break;
}
else
tokens.back() += c; // append to existing string
}

Or, if you like goto statements:

std::vector<std::string> tokens;
std::string delims = " \n()";
char c;
while (f.get(c))
if (delims.find(c) != tokens.end())
add_token:
tokens.emplace_back(1, c);
else
{
tokens.emplace_back(1, c); // start new string
while (f.get(c))
if (delims.find(c) != tokens.end())
goto add_token;
else
tokens.back() += c; // append to existing string
}

Which is "easier" to grok is debatable....

how can i split a vector string and acces what i need in it?

As user31264 suggested you could write a split function and split every line you got into its words.

IMHO this is a better and more flexible split function though:

#include <vector>
#include <string>
#include <sstream>
std::vector<std::string> split(const std::string& str, char delimiter)
{
std::vector<std::string> tokens;
std::string token;
std::istringstream tokenStream(str);
while(std::getline(tokenStream, token, delimiter)) {
tokens.push_back(token);
}
return tokens;
}

What that function does is creating a stringstream out of your string (your line) and extracting words delimited by char delimiter by using getline() on that stream.

So while reading your file with getline() you could pass every line into that split function with

auto words = split(line, ' ');

and iterate over all words that line contains.



Related Topics



Leave a reply



Submit