12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <assert.h>
- size_t split_count(char* a_str, const char a_delim) {
- char* tmp = a_str;
- char* last_comma = 0;
- size_t count = 0;
- while (*tmp) {
- if (a_delim == *tmp) {
- count++;
- last_comma = tmp;
- }
- tmp++;
- }
- // Add space for trailing token.
- count += last_comma < (a_str + strlen(a_str) - 1);
- // Add space for terminating null string.
- count++;
- return count;
- }
- /* Adapted from http://stackoverflow.com/a/9210560 */
- char** str_split(char* a_str, const char a_delim) {
- char delim[2];
- delim[0] = a_delim;
- delim[1] = 0;
- size_t count = split_count(a_str, a_delim);
- char** result = malloc(sizeof(char*) * count);
- if(!result) {
- fprintf(stderr, "Failed to allocate memory when splitting string '%s'.\n", a_str);
- return NULL;
- }
- if(result) {
- size_t idx = 0;
- char* token = strtok(a_str, delim);
- while (token) {
- assert(idx < count);
- *(result + idx++) = strdup(token);
- token = strtok(0, delim);
- }
- assert(idx == count - 1);
- *(result + idx) = 0;
- }
- return result;
- }
- void substring(char* substr, const char* string, size_t start, size_t end) {
- if(end > strlen(string)) {
- end = strlen(string);
- }
- if(start < 0) {
- start = 0;
- }
- if(end < start) {
- return NULL;
- }
- size_t nchars = end - start + 1; // Need +1 because substring should include both ends.
- memcpy(substr, &string[start], nchars);
- substr[nchars] = '\0';
- }
- /* Adapted from http://stackoverflow.com/a/12890107 */
- char* replace(const char *src, char ch, const char *repl) {
- int count = 0;
- const char *tmp;
- for(tmp=src; *tmp; tmp++)
- count += (*tmp == ch);
- size_t rlen = strlen(repl);
- char *res = malloc(strlen(src) + (rlen-1)*count + 1);
- char *ptr = res;
- for(tmp=src; *tmp; tmp++) {
- if(*tmp == ch) {
- memcpy(ptr, repl, rlen);
- ptr += rlen;
- } else {
- *ptr++ = *tmp;
- }
- }
- *ptr = 0;
- return res;
- }
|