libstr.c (1121B)
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 #include <stdarg.h> 5 6 #include "libstr.h" 7 8 void str_append_len(char **buffer, char *value, int len) { 9 int buffer_len = 0; 10 if (*buffer != NULL) { 11 buffer_len = strlen(*buffer); 12 } 13 *buffer = realloc(*buffer, sizeof(char) * (buffer_len + len + 1)); 14 memcpy(*buffer + buffer_len, value, len); 15 (*buffer)[buffer_len + len] = '\0'; 16 } 17 18 void str_append(char **buffer, char *value) { 19 int len = strlen(value); 20 str_append_len(buffer, value, len); 21 } 22 23 void str_appendf(char **buffer, const char *format, ...) { 24 va_list args; 25 va_start(args, format); 26 char str[1000]; 27 vsnprintf(str, sizeof(str), format, args); 28 str_append(buffer, str); 29 va_end(args); 30 } 31 32 char *str_replace_all(char *buffer, char *str, char *replacement) { 33 char *result = NULL; 34 int str_len = strlen(str); 35 for (int i = 0; i < (int) strlen(buffer); i++) { 36 char *ptr = &buffer[i]; 37 if (strncmp(ptr, str, str_len) == 0) { 38 str_append(&result, replacement); 39 i += str_len - 1; 40 } 41 else { 42 str_append_len(&result, &buffer[i], 1); 43 } 44 } 45 return result; 46 }