home / fornax-v3-0 / src / libs / strings.h

strings.h



//
//  strings.h
//  fornax3
//
//  Created by Anders on 24/04/2019.
//

#ifndef strings_h
#define strings_h

#include <stdbool.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>

static inline void strings_copy(char *copy, const char *str) {
    strcpy(copy, str);
}

static inline char* strings_copy_alloc(const char* str) {
    size_t len = strlen(str);
    char* copy = (char*) malloc(len + 1);
    strings_copy(copy, str);
    return copy;
}

static inline int strings_split(char* source, char** dest, const char* delim) {
  int i = 0;
  char *ptr = strtok(source, delim);
  while(ptr != NULL) {
    dest[i] = ptr;
    i++;
    ptr = strtok(NULL, delim);
  }
  return i;
}

static inline bool string_equals(const char *s1, const char *s2) {
  return !strcmp(s1, s2);
}

static inline bool string_starts_with(const char *string, const char *prefix) {
  if(strncmp(string, prefix, strlen(prefix)) == 0) return true;
  return false;
}

static inline char *strings_trim(char *str) {
  char *end;
  
  while(isspace((unsigned char)*str)) str++;
  
  if(*str == 0)
    return str;
  
  end = str + strlen(str) - 1;
  while(end > str && isspace((unsigned char)*end)) end--;
  
  end[1] = '\0';
  
  return str;
}

static inline long string_to_long(const char* string) {
  return strtol(string, NULL, 10);
}

#endif /* strings_h */