Skip to content

Instantly share code, notes, and snippets.

@lilrooness
Last active November 17, 2021 22:00
Show Gist options
  • Select an option

  • Save lilrooness/49702269ba561eed24eaf66f292c424d to your computer and use it in GitHub Desktop.

Select an option

Save lilrooness/49702269ba561eed24eaf66f292c424d to your computer and use it in GitHub Desktop.
Split an STL string without using STL just because
#include <string>
#include "stdio.h"
#include "string.h"
int _get_first_string_chunk(
const char *in,
char *out_buffer,
int buffer_length,
char delimiter,
int *out_size,
int *out_leading_delimiters
) {
int i = 0;
bool leading_delimiter = true;
int leading_delimiter_offset = i;
while (in[i] != '\0') {
if (in[i] == delimiter && !leading_delimiter) {
if (buffer_length < i) {
std::cout << "CRASH EXPECTED ERROR: _get_first_string_chunk: buffer_length < i" << std::endl;
}
strncpy(out_buffer, in+leading_delimiter_offset, i - leading_delimiter_offset);
out_buffer[i] = '\0';
*out_size = i - leading_delimiter_offset;
*out_leading_delimiters = leading_delimiter_offset;
return i - leading_delimiter_offset;
} else if(in[i] != delimiter && leading_delimiter) {
leading_delimiter = false;
leading_delimiter_offset = i;
}
i += 1;
}
strncpy(out_buffer, in+leading_delimiter_offset, i - leading_delimiter_offset);
out_buffer[i] = '\0';
*out_size = i - leading_delimiter_offset;
*out_leading_delimiters = leading_delimiter_offset;
return i - leading_delimiter_offset;
}
void split_string(std::string in, std::vector<std::string> *chunks, char delimiter) {
char buffer[100];
char *in_ptr = (char*) in.c_str();
int chunk_len;
int leading_delimiters;
while(_get_first_string_chunk(in_ptr, buffer, 100, delimiter, &chunk_len, &leading_delimiters) != 0) {
std::string chunk;
for (int i=0; i<chunk_len; i++) {
chunk += buffer[i];
}
chunks->push_back(chunk);
in_ptr += chunk_len + leading_delimiters;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment