Python C++: is the any python.split() like method in c++? [duplicate] - c++

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I tokenize a string in C++?
Splitting a string in C++
Is there any python.split(",") like method in C++ please.

Got the following code from some where .. might help
#define MAIN 1
#include <string>
#include <vector>
#include <iostream>
using namespace std;
class splitstring : public string {
vector<string> flds;
public:
splitstring(char *s) : string(s) { };
vector<string>& split(char delim, int rep=0);
};
vector<string>& splitstring::split(char delim, int rep) {
if (!flds.empty()) flds.clear();
string work = data();
string buf = "";
int i = 0;
while (i < work.length()) {
if (work[i] != delim)
buf += work[i];
else if (rep == 1) {
flds.push_back(buf);
buf = "";
} else if (buf.length() > 0) {
flds.push_back(buf);
buf = "";
}
i++;
}
if (!buf.empty())
flds.push_back(buf);
return flds;
}
#ifdef MAIN
main()
{
splitstring s("Humpty Dumpty sat on a wall. Humpty Dumpty had a great fall");
cout << s << endl;
vector<string> flds = s.split(' ');
for (int k = 0; k < flds.size(); k++)
cout << k << " => " << flds[k] << endl;
cout << endl << "with repeated delimiters:" << endl;
vector<string> flds2 = s.split(' ', 1);
for (int k = 0; k < flds2.size(); k++)
cout << k << " => " << flds2[k] << endl;
}
#endif
In boost:
vector<string> results;
boost::split(results, line, boost::is_any_of("#"));
In STL:
template <typename E, typename C>
size_t split(std::basic_string<E> const& s, C &container,
E const delimiter, bool keepBlankFields = true) {
size_t n = 0;
std::basic_string<E>::const_iterator it = s.begin(), end = s.end(), first;
for (first = it; it != end; ++it) {
if (delimiter == *it) {
if (keepBlankFields || first != it) {
container.push_back(std::basic_string<E > (first, it));
++n;
first = it + 1;
} else ++first;
}
}
if (keepBlankFields || first != it) {
container.push_back(std::basic_string<E > (first, it));
++n;
}
return n;
}

Related

C++ How to write a code that counts top words while removing any special characters from text file

How do I take a text file from the command line that opens and reads it, and then count the top words in that file but also removes any special characters. I have this code done here and used maps but it isn't counting every word. For instance "hello." is one word and also "$#%hello<>?/". I have this file from the song shake it off that's supposed to read shake 78 times but I only counted 26 in this code.
#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <vector>
using namespace std;
string ask(const string& msg) {
string ans;
cout << msg;
getline(cin, ans);
return ans;
}
int main() {
ifstream fin( ask("Enter file name: ").c_str() ) ;
if (fin.fail()) {
cerr << "ERROR"; // this is if the file fails to open
return 1;
}
map<string, int> wordCount;
string entity;
while (fin >> entity) {
vector<string> words;
for (int i = 0, a = 0; i < entity.length(); i++) {
char& c = entity[i];
if (c < 'A' || (c > 'Z' && c < 'a') || c > 'z') {
string word = entity.substr(a, i - a);
a = i + 1;
if (word.length() > 0)
words.push_back(word);
}
}
for (auto & word : words)
wordCount[word]++;
}
fin.close();
vector<string> topWords;
const size_t MAX_WORDS = 10;
for ( auto iter = wordCount.begin(); iter != wordCount.end(); iter ++ ) {
int som = 0, lim = topWords.size();
while (som < lim) {
int i = ( som + lim ) / 2;
int count = wordCount[topWords[i]];
if ( iter -> second > count)
lim = i;
else if ( iter -> second < count )
som = i + 1;
else
som = lim = i;
}
if (som < MAX_WORDS ) {
topWords.insert( topWords.begin() + som, iter -> first );
if ( topWords.size() > MAX_WORDS )
topWords.pop_back();
}
}
for (auto & topWord : topWords)
cout << "(" << wordCount[topWord] << ")\t" << topWord << endl;
return 0;
}
One last thing if yall can probably help me on is how would I also write a code that takes a number from the command line alongside the filename and with that number, display the number of top words corresponding with that number passed in the command line, I would assume there is a parse args involved maybe.
Thank you again!
https://s3.amazonaws.com/mimirplatform.production/files/48a9fa64-cddc-4e45-817f-3e16bd7772c2/shake_it_off.txt
!hi!
#hi#
#hi#
$hi$
%hi%
^hi^
&hi&
*hi*
(hi(
)hi)
_hi_
-hi-
+hi+
=hi=
~hi~
`hi`
:hi:
;hi;
'hi'
"hi"
<hi<
>hi>
/hi/
?hi?
{hi{
}hi}
[hi[
]hi]
|hi|
\hi\
bob bob bob bob bob bob bob !###$$%#&#^*()#*#)_++(#<><#:":bob###$$%#&#^*()#*#)_++(#<><#:":
!###$$%#&#^*()#*#)_++(#<><#:":bob###$$%#&#^*()#*#)_++(#<><#:": !###$$%#&#^*()#*#)_++(#<><#:":bob###$$%#&#^*()#*#)_++(#<><#:":
!###$$%#&#^*()#*#)_++(#<><#:":bob###$$%#&#^*()#*#)_++(#<><#:": !###$$%#&#^*()#*#)_++(#<><#:":bob###$$%#&#^*()#*#)_++(#<><#:
this is the special character test
Your original code is somewhat hard to refine, I have followed your description to get a program that uses STL.
Combine erase with remove_if to remove unwanted chars
Use set to resort by counts
If you have some experience with Boost, it's a use case with multimap or bimap, which can make the code even more cleaner.
#include <algorithm>
#include <fstream>
#include <iostream>
#include <map>
#include <set>
#include <string>
#include <vector>
using namespace std;
string ask(const string& msg) {
string ans;
cout << msg;
getline(cin, ans);
return ans;
}
int main() {
// ifstream fin(ask("Enter file name: ").c_str());
ifstream fin("shake_it_off.txt");
if (fin.fail()) {
cerr << "ERROR"; // this is if the file fails to open
return 1;
}
map<string, size_t> wordCount;
string entity;
while (fin >> entity) {
entity.erase(std::remove_if(entity.begin(), entity.end(),
[](char ch) { return !isalpha(ch); }),
entity.end());
wordCount[entity] += 1;
}
auto cmp = [](const std::pair<std::string, size_t>& lhs,
const std::pair<std::string, size_t>& rhs) {
return lhs.second > rhs.second;
};
std::multiset<std::pair<std::string, size_t>, decltype(cmp)> top(
wordCount.begin(), wordCount.end(), cmp);
auto it = top.begin();
const size_t MAX_WORDS = 10;
for (size_t i = 0; i < MAX_WORDS && it != top.end(); ++i, ++it) {
cout << "(" << it->first << ")\t" << it->second << endl;
}
return 0;
}

Implementing an alphabet in C++

I'm making a code for cipher that reads alphabet in it's binary code. Is there a way to implement custom alphabet (not using ASCII)? For example alphabet={a,b,c,d,e,...,z,],[,.,..., ,-} and for each character there's a number 0,1,...,63. So, the bijetion will be from element of alphabet to 6 bit number.
How to make this implementation using simple functions in C++? I tried to make a strings length 1 and corresponding number using if statements and then plug them into .txt file, but it didn't work out.
string str1, ..., str63;
string sometext;
str1 = 'a';
// ...
cin >> sometext;
int k;
k = sometext.length();
string res;
ofstream out;
out.open("cipher.txt");
for (int i = 0; i < k; i++) {
res = sometext.substr(i, 1);
if (res == str1) {
res = '000000';
}
// ...
if (res == str63) {
res = '111111';
}
out << res;
}
I made a simple class Alphabet achieving your task. It uses std::unordered_map to store mapping between characters and binary representation, and uses this mapping to convert between those two representations. Also it computes binary representation. Class can be given any alphabet.
For testing I do two conversions between char and binary and output results to console. If requested values are out of range then std::exception is thrown.
Try it online!
#include <string>
#include <unordered_map>
#include <cmath>
#include <stdexcept>
#include <iostream>
class Alphabet {
public:
Alphabet(std::string const & _chars)
: chars(_chars) {
size_t num_bits = std::ceil(std::log(std::max(size_t(1), chars.size()))
/ std::log(2) - 1e-6);
for (size_t i = 0; i < chars.size(); ++i) {
std::string bin;
for (ptrdiff_t j = num_bits - 1; j >= 0; --j)
bin += i & (1 << j) ? "1" : "0";
c2b[chars[i]] = bin;
b2c[bin] = chars[i];
}
}
std::string ToBin(char c) const {
auto it = c2b.find(c);
if (it == c2b.end())
throw std::runtime_error("Character '" +
std::string(1, c) + "' not in alphabet!");
return it->second;
}
char ToChar(std::string const & bin) const {
auto it = b2c.find(bin);
if (it == b2c.end())
throw std::runtime_error("Binary '" + bin + "' is out of range!");
return it->second;
}
std::string const & Chars() const {
return chars;
}
private:
std::string chars;
std::unordered_map<char, std::string> c2b;
std::unordered_map<std::string, char> b2c;
};
int main() {
try {
Alphabet alph("abcdef{}123");
std::cout << alph.ToBin('f') << std::endl;
std::cout << alph.ToChar("0011") << std::endl;
std::cout << alph.Chars() << std::endl;
return 0;
} catch (std::exception const & ex) {
std::cout << "Exception: " << ex.what() << std::endl;
return -1;
}
}
Output:
0101
d
abcdef{}123

Solve linear equation with Maps

I have almost completed the coding to solve simple linear equation set. Just seem to missing something in the recursive call with Maps causing issue.
Here is the problem statement to solve, example:
X = Y + 2
Y = Z + R + 1
R = 2 + 3
Z = 1
Given: LHS would be just variable names. RHS would have only variables, unsigned int and '+' operator. Solve for all unknowns.
Solution that I get with my code:
X = 2
Y = 1
R = 5
Z = 1
My code :
#include <vector>
#include <string>
#include <sstream>
#include <iostream>
#include <map>
#include <fstream>
#include <set>
#include <regex>
using namespace std;
map<string, string> mymap;
// Method to Parse a given expression based on given arg delimiter
// ret: vector of parsed expression
vector<string> parse_expr(string n, char *delims)
{
vector<string> v;
string cleanline;
char* char_line = (char*)n.c_str(); // Non-const cast required.
char* token = NULL;
char* context = NULL;
vector<string>::iterator it;
token = strtok_s(char_line, delims, &context);
while (token != NULL)
{
cleanline += token;
cleanline += ' ';
v.push_back(token);
token = strtok_s(NULL, delims, &context);
}
return v;
}
//Method to find sum for a given vector
//retype: string
//ret: sum of given vector
string find_VctrSum(string key, vector<string> v)
{
int sum = 0;
string val;
vector<string>::iterator i;
for (i = v.begin(); i != v.end(); i++)
{
val = *i;
//cout << "val is :" << val << endl;
sum += stoi(val);
}
return to_string(sum);
}
//Method to check if arg is integer or string
// ret: True if int
bool isNumber(string x) {
regex e("^-?\\d+");
if (regex_match(x, e)) return true;
else return false;
}
//Recursive call to evaluate the set of expressions
string evaluate_eq(string key)
{
string expr, var;
vector<string> items;
vector<string>::iterator i;
auto temp = mymap.find(key);
if (temp != mymap.end()) // check temp is pointing to underneath element of a map
{
//fetch lhs
var = temp->first;
//fetch rhs
expr = temp->second;
}
// remove whitespaces
expr.erase(remove_if(expr.begin(), expr.end(), isspace), expr.end());
//Parse RHS by '+' sign
items = parse_expr(expr, "+");
for (i = items.begin(); i != items.end(); i++)
{
//cout << (*i) << endl;
if (isNumber(*i) == true)
{
//pass- do nothiing
}
else
{
//recursive call to evaluate unknown
string c = evaluate_eq(*i);
//now update the map and Find Sum vector
mymap[key] = c;
*i = c;
}
}
//find sum
return find_VctrSum(key, items);
}
//main to parse input from text file and evaluate
int main()
{
string line;
ifstream myfile("equation.txt");
vector<string> v;
if (myfile.is_open())
{
while (getline(myfile, line))
{
v.push_back(line);
}
myfile.close();
}
else cout << "Unable to open file";
//Create a map with key:variable and value: expression to solve
for (int i = 0; i < v.size(); i++)
{
vector<string> token;
token = parse_expr(v[i], "=");
mymap.insert(pair<string, string>(token[0], token[1]));
}
cout << "Equation sets given:" << endl;
for (map<string, string>::iterator it = mymap.begin(); it != mymap.end(); ++it)
{
std::cout << it->first << " => " << it->second << '\n';
}
for (map<string, string>::iterator it = mymap.begin(); it != mymap.end(); it++)
{
//Also update the map
mymap[it->first] = evaluate_eq(it->first);
}
cout << "Equation sets solved:" << endl;
for (map<string, string>::iterator it = mymap.begin(); it != mymap.end(); ++it)
{
std::cout << it->first << " => " << it->second << '\n';
}
char ch;
cin >> ch;
}
Logic is to call recursively for any unknown (string) if found while resolving a given expression and update the map with values. On debugging, I could see that my recursive call fails at below, but I see "mymap" is being updated. Not sure why.
if (temp != mymap.end())
Any help in identifying the issue or any logical lapse would be much appreciated.
Thanks
After fixing couple of logic, my code works correctly.
In main()
While, creating the input map create by striping whitespace
//Create a map with key:variable and value: expression to solve
for (int i = 0; i < v.size(); i++)
{
vector<string> token;
token = parse_expr(v[i], "=");
//Strip whitespaces
token[0].erase(remove_if(token[0].begin(), token[0].end(), isspace), token[0].end());
token[1].erase(remove_if(token[1].begin(), token[1].end(), isspace), token[1].end());
mymap.insert(pair<string, string>(token[0], token[1]));
}
This eliminate my issue of finding key in the map -
if (temp != mymap.end())
Updated my find_VctrSum to update the map here, unlike my earlier attempt to update in evaluate_eq().
//Method to find sum for a given vector
//retype: string
//ret: sum of given vector
string find_VctrSum(string key, vector<string> v)
{
int sum = 0;
string val;
vector<string>::iterator i;
for (i = v.begin(); i != v.end(); i++)
{
val = *i;
sum += stoi(val);
}
//Update the Map
mymap[key] = to_string(sum);
return to_string(sum);
}
Here is the complete working code -
#include <vector>
#include <string>
#include <sstream>
#include <iostream>
#include <map>
#include <fstream>
#include <set>
#include <regex>
using namespace std;
map<string, string> mymap;
// Method to Parse a given expression based on given arg delimiter
// ret: vector of parsed expression
vector<string> parse_expr(string n, char *delims)
{
vector<string> v;
string cleanline;
char* char_line = (char*)n.c_str(); // Non-const cast required.
char* token = NULL;
char* context = NULL;
vector<string>::iterator it;
token = strtok_s(char_line, delims, &context);
while (token != NULL)
{
cleanline += token;
cleanline += ' ';
v.push_back(token);
token = strtok_s(NULL, delims, &context);
}
return v;
}
//Method to find sum for a given vector
//retype: string
//ret: sum of given vector
string find_VctrSum(string key, vector<string> v)
{
int sum = 0;
string val;
vector<string>::iterator i;
for (i = v.begin(); i != v.end(); i++)
{
val = *i;
sum += stoi(val);
}
//Update the Map
mymap[key] = to_string(sum);
return to_string(sum);
}
//Method to check if arg is integer or string
// ret: True if int
bool isNumber(string x) {
regex e("^-?\\d+");
if (regex_match(x, e)) return true;
else return false;
}
//Recursive call to evaluate the set of expressions
string evaluate_eq(string key)
{
string expr, var;
vector<string> items;
vector<string>::iterator i;
string currentkey = key;
auto temp = mymap.find(key);
if (temp != mymap.end()) // check temp is pointing to underneath element of a map
{
//fetch lhs
var = key;
//fetch rhs
expr = temp->second;
}
// remove whitespaces
expr.erase(remove_if(expr.begin(), expr.end(), isspace), expr.end());
//Parse RHS by '+' sign
items = parse_expr(expr, "+");
for (i = items.begin(); i != items.end(); i++)
{
if (isNumber(*i) == true)
{
//pass- do nothiing
}
else
{
//recursive call to evaluate unknown
string c = evaluate_eq(*i);
//update the temp vector
*i = c;
}
}
//find sum
return find_VctrSum(key, items);
}
//main to parse input from text file and evaluate
int main()
{
string line;
ifstream myfile("equation.txt");
vector<string> v;
if (myfile.is_open())
{
while (getline(myfile, line))
{
v.push_back(line);
}
myfile.close();
}
else cout << "Unable to open file";
//Create a map with key:variable and value: expression to solve
for (int i = 0; i < v.size(); i++)
{
vector<string> token;
token = parse_expr(v[i], "=");
//Strip whitespaces
token[0].erase(remove_if(token[0].begin(), token[0].end(), isspace), token[0].end());
token[1].erase(remove_if(token[1].begin(), token[1].end(), isspace), token[1].end());
mymap.insert(pair<string, string>(token[0], token[1]));
}
cout << "Equation sets given:" << endl;
for (map<string, string>::iterator it = mymap.begin(); it != mymap.end(); ++it)
{
std::cout << it->first << " => " << it->second << '\n';
}
for (map<string, string>::iterator it = mymap.begin(); it != mymap.end(); it++)
{
//Also update the map
mymap[it->first] = evaluate_eq(it->first);
}
cout << "Equation sets solved:" << endl;
for (map<string, string>::iterator it = mymap.begin(); it != mymap.end(); ++it)
{
std::cout << it->first << " => " << it->second << '\n';
}
char ch;
cin >> ch;
}

how to access vector of map of ( int and vector of strings )

how do i access map of int and vectors of string in the passed_vector function.
I just want to print them in that function.
#include <iostream>
#include <vector>
#include <map>
#include <string>
using namespace std;
typedef vector< map< int, vector<string> > > vmis;
typedef map< int, vector<string> > mis;
typedef vector<string> vstr;
void passing_vector(const vmis &meetings);
//return size of vector
template< typename A > size_t n_elements( const A& a )
{
return sizeof a / sizeof a[ 0 ];
}
int main()
{
vmis meeting_info;
mis meeting_members;
vstr sw_vec;
vstr sys_vec;
string sw_team[] = {"Ricky", "John", "David"};
string sys_team[] = {"Simmon", "Brad", "Schmidt", "Fizio"};
sw_vec.insert(sw_vec.begin(), sw_team, sw_team + n_elements(sw_team) );
sys_vec.insert(sys_vec.begin(), sys_team, sys_team + n_elements(sys_team) );
meeting_members.insert(make_pair(520, sw_vec));
meeting_members.insert(make_pair(440, sys_vec));
meeting_info.push_back(meeting_members);
passing_vector(meeting_info);
return 0;
}
void passing_vector(const vmis &meetings)
{
vmis::iterator itvmis = meetings.begin();
//how do i access map of int and vectors of string.
//I just want to print them.
}
I know how to print them in main function.
vmis::iterator itvims = meeting_info.begin();
for( int i = 0; i < meeting_info.size(); i++ )
{
mis::iterator itm = meeting_members.begin();
for(itm; itm != meeting_members.end(); itm++ )
{
cout << itm->first << " : ";
vstr::iterator it = itm->second.begin();
for(it; it != itm->second.end(); it++)
cout << *it << " ";
cout << endl;
}
}
desired output
440 : Simmon Brad Schmidt Fizio
520 : Ricky John David
if there is a better way of doing this suggestions are always welcome.
The easiest aproach is to use auto, also since your meetings is const, you need to use const_iterator:
void passing_vector(const vmis &meetings)
{
vmis::const_iterator itvims = meetings.begin();
//how do i access map of int and vectors of string.
//I just want to print them.
for (;itvims != meetings.end(); ++itvims)
{
const auto& map_item = *itvims;
for (const auto& map_it : map_item)
{
int map_key = map_it.first;
const auto& str_vec = map_it.second;
for (const auto& str : str_vec)
{
std::cout << map_key << " - " << str << "\n";
}
}
}
}
[edit]
c++98 version:
void passing_vector(const vmis &meetings)
{
vmis::const_iterator itvims = meetings.begin();
//how do i access map of int and vectors of string.
//I just want to print them.
for (;itvims != meetings.end(); ++itvims)
{
const mis& map_item = *itvims;
for (mis::const_iterator map_it = map_item.begin(); map_it != map_item.end(); ++map_it)
{
int map_key = map_it->first;
const vstr& str_vec = map_it->second;
for (vstr::const_iterator sitr = str_vec.begin(); sitr != str_vec.end(); ++sitr)
{
std::cout << map_key << " - " << *sitr << "\n";
}
}
}
}

Split a string on multiple multi-char delimeters in C++

How can I split a string on multiple multi-character delimiters?
I want a function like vector<string> split_string(string input, vector<string> delims)
For example, split_string("foo+bar := baz",{"+"," ",":="}) = {"foo","+","bar"," "," ",":="," ","baz"}
My cut at the same. I chose to go with divide and conquer. It is not fast. It is not efficient. But it is simple.
Unfortunately it didn't work in this case because we are preserving the delimiters in the output. Dividing allowed later delimiters to split previously found delimiters.
Eg:
Source :=foo+bar . :=baz+quaax:= C++
Delims [+][ ][:=][:]
Result [:][=][foo][+][bar][ ][ ][.][ ][ ][ ][:][=][baz][+][quaax][:][=][ ][ ][C][+][+]
Yuck.
Finally settled on a similar approach to jafar's and added it to my support library to try out in a job I'm working on to replace the divide and conquer approach because it does look to be faster. Wouldn't have bothered posting this, but Jafar's is a bit over complicated for my tastes. Haven't done any profiling so his may be faster.
#include <iostream>
#include <vector>
// easy vector output
template<class TYPE>
std::ostream & operator<<(std::ostream & out,
const std::vector<TYPE> & in)
{
for (const TYPE &val: in)
{
out << "["<< val << "]";
}
return out;
}
// find the first of many string delimiters
size_t multifind(size_t start,
const std::string & source,
const std::vector<std::string> &delims,
size_t & delfound)
{
size_t lowest = std::string::npos;
for (size_t i = 0; i < delims.size(); i++)
{
size_t pos = source.find(delims[i], start);
if (pos == start)
{
lowest = pos;
delfound = i;
break;
}
else if (pos < lowest)
{
lowest = pos;
delfound = i;
}
}
return lowest;
}
// do the grunt work
std::vector<std::string> splitString(const std::string &source,
const std::vector<std::string> &delims)
{
std::vector<std::string> tokens;
size_t current = 0;
size_t delfound;
size_t next = multifind(current,
source,
delims,
delfound);
while(next != std::string::npos)
{
if (current < next)
{
tokens.push_back(source.substr(current, next - current));
}
tokens.push_back(delims[delfound]);
current = next + delims[delfound].length();
next = multifind(current,
source,
delims,
delfound);
}
if (current < source.length())
{
tokens.push_back(source.substr(current, std::string::npos));
}
return tokens;
}
void test(const std::string &source,
const std::vector<std::string> &delims)
{
std::cout << "Source " << source << std::endl;
std::cout << "Delims " << delims << std::endl;
std::cout << "Result " << splitString(source, delims) << std::endl << std::endl;
}
int main()
{
test(":=foo+bar . :=baz+quaax:= C++", { " ",":=","+" });
test(":=foo+bar . :=baz+quaax:= C++", { ":=","+"," " });
test(":=foo+bar . :=baz+quaax:= C++", { "+"," ",":=" });
test(":=foo+bar . :=baz+quaax:= C++", { "+"," ",":=",":" });
test(":=foo+bar . :=baz+quaax:= C++", { ":"," ",":=","+" });
test("foo+bar . :=baz+quaax:= C++lalala", { "+"," ",":=",":" });
}
Try this
#include <iostream>
#include <string>
#include <vector>
#include <map>
std::vector<std::string> splitString(std::string input, std::vector<std::string> delimeters);
std::string findFirstOf(std::string input, std::vector<std::string> del);
int main()
{
std::vector<std::string> words = splitString(":=foo+bar :=baz+quaax", { " ",":=","+" });
for (std::string str : words)
std::cout << str << ",";
std::cout << std::endl;
system("pause");
}
std::vector<std::string> splitString(std::string input, std::vector<std::string> delimeters)
{
std::vector<std::string> result;
size_t pos = 0;
std::string token;
std::string delimeter = findFirstOf(input, delimeters);
while(delimeter != "")
{
if ((pos = input.find(delimeter)) != std::string::npos)
{
token = input.substr(0, pos);
result.push_back(token);
result.push_back(delimeter);
input.erase(0, pos + delimeter.length());
}
delimeter = findFirstOf(input, delimeters);
}
result.push_back(input);
return result;
}
//find the first delimeter in the string
std::string findFirstOf(std::string input, std::vector<std::string> del)
{
//get a map of delimeter and position of delimeter
size_t pos;
std::map<std::string, size_t> m;
for (int i = 0; i < del.size(); i++)
{
pos = input.find(del[i]);
if (pos != std::string::npos)
m[del[i]] = pos;
}
//find the smallest position of all delimeters i.e, find the smallest value in the map
if (m.size() == 0)
return "";
size_t v = m.begin()->second;
std::string k = m.begin()->first;
for (auto it = m.begin(); it != m.end(); it++)
{
if (it->second < v)
{
v = it->second;
k = it->first;
}
}
return k;
}
output: ,:=,foo,+,bar, ,,:=,baz,+,quaax,.