GAME: Play the number guessing game -> PLAY NOW

libstr.h - libstr - A util library for dealing with strings in C

libstr

A util library for dealing with strings in C
git clone git@soophie.de:/srv/git/libstr
log | files | refs | readme

libstr.h (1437B)


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