Skip to content

Instantly share code, notes, and snippets.

@eoconnell
Created May 26, 2011 20:52
Show Gist options
  • Save eoconnell/994053 to your computer and use it in GitHub Desktop.
Save eoconnell/994053 to your computer and use it in GitHub Desktop.
PHP explode and trim in C++
#include <string>
#include <vector>
/* Trims a string of any characters provided in the char list */
string trim(string str, string charlist = " \t\f\v\n\r")
{
int first, last;
last = str.find_last_not_of(charlist);
// only contains chars that are being trimmed, return ""
if (last == string::npos)
{
return "";
}
first = str.find_first_not_of(charlist);
if (first == string::npos)
{
first = 0;
}
return str.substr(first, (last-first)+1);
}
/* Returns a vector of strings, each of which is a substring formed
by splitting it on boundaries formed by the string delmiter. */
vector<string> explode(string delim, string str)
{
size_t left = 0; // left bound
size_t right = 0; // right bound
size_t delim_len = delim.length();
size_t str_len = str.length();
vector<string> result;
// that was easy...
if ((str = trim(str)).empty())
{
return result;
}
// add each substring to the vector between delimiters
do
{
right = str.find(delim, left);
result.push_back(str.substr(left, right-left));
left = right + delim_len;
} while (right < str_len);
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment