Skip to content

Instantly share code, notes, and snippets.

@RichardB01
Created January 15, 2023 10:28
Show Gist options
  • Save RichardB01/b282a2da89a63e0844f32a834839cf8e to your computer and use it in GitHub Desktop.
Save RichardB01/b282a2da89a63e0844f32a834839cf8e to your computer and use it in GitHub Desktop.
A function that splits a string into substrings in C++.
#include <deque>
#include <string>
using namespace std;
/**
* Split a string into a sequence of substrings according to
* a deliminator.
* @param[in] str The string to split.
* @param[in] delim The deliminator of substrings.
* @param[out] The sequence of split strings.
*/
deque<string> splitstring(string str, char delim) {
deque<string> splitstrings;
string charbuffer;
/**
* Iterate each character in the string and push it to a character buffer.
* When the deliminating character is read, copy the contents of the
* character buffer into the split strings sequence while clearing the
* buffer's contents.
*/
for (uint32_t charindex = 0u; charindex < str.length(); charindex++) {
char readchar;
readchar = str.at(charindex);
if (readchar != delim) {
charbuffer.push_back(readchar);
} else {
splitstrings.push_back(charbuffer);
charbuffer.clear();
}
}
/**
* If there are trialing characters in the input string
* there will be some characters left in the buffer, so
* copy the leftover characters into the split strings sequence
* too.
*/
if (!charbuffer.empty()) {
splitstrings.push_back(charbuffer);
charbuffer.clear();
} else {
}
return splitstrings;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment