I have to say that these functions are handy. Here they are:
Code: Select all
#ifndef STRING_UTILS_H_INCLUDED
#define STRING_UTILS_H_INCLUDED
//
//Header file containing custom string utility functions
//
// List of functions:
// explode(const string &delim, const string &str)
// returns an array of substrings parsed from the input string
//
// implode(const string &glue, const vector<string> &strs)
// returns a string formed from the vector elements of strs, with glue between each element
//
//
#include <iostream>
#include <vector>
#include <string>
using namespace std;
//
//Function Prototypes:
//
vector<string> explode(const string &delim, const string &str);
string implode(const string &glue, const vector<string> &strs);
//
//function definitions for string_utils functions
//
vector<string> explode(const string &delim, const string &str)
{
vector<string> result;
int delim_length = delim.length(); //So that length is calculated once
int str_length = str.length(); //So that length is calculated once
if (delim_length==0)
{
return(result);
}
else
{
int i=0;
int j=0;
int k=0;
while(i < str_length)
{
while (i + (j<str_length) && (j<delim_length) && (str[i+j]==delim[j]))
{
j++;
}
if (j==delim_length)//found delimiter
{
result.push_back(str.substr(k, i-k));
i+=delim_length;
k=i;
}
else
{
i++;
}
}
result.push_back(str.substr(k, i-k));
return(result);
}
}
string implode(const string &glue, const vector<string> &strs)
{
string a;
int i;
int str_size= strs.size();
for(i=0; i < str_size; ++i)
{
a+= strs[i];
if (i < (str_size-1))
{
a+= glue;
}
}
return(a);
}
#endif // STRING_UTILS_H_INCLUDED