TGAM123

string_explode

May 18th, 2016
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.13 KB | None | 0 0
  1. //HEADER string_explode.h
  2. /**
  3.  * @author Tibor Dancs (433610) @ fi.muni.cz
  4.  */
  5. #ifndef STRING_EXPLODE.H
  6. #define STRING_EXPLODE.H
  7.  
  8. #include <string.h>
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11.  
  12. /**
  13.  * @brief explode Takes char* in as formated input and const char *separator as priority heap of separators
  14.  * @param in char* formated input
  15.  * @param separator const char* priority heap of separators
  16.  * @return original char array if no separator matched, single string if locateb between any {start of input, separator, end of string} or NULL if no strings to parse
  17.  */
  18. char *explode(char *in, const char *separator);
  19.  
  20. #endif
  21.  
  22. //SOURCE string_explode.c
  23. /**
  24.  * @author Tibor Dancs (433610) @ fi.muni.cz
  25.  */
  26. #include "string_explode.h"
  27. char *explode(char *in, const char *separator) {
  28.  
  29.     static char *pos;
  30.  
  31.     if (!separator || !strcmp(separator,"")){
  32.         if (pos){
  33.             free(pos);
  34.             pos = NULL;
  35.         }
  36.         return in;
  37.     }
  38.  
  39.     char *ret;
  40.  
  41.     if (in) {
  42.         pos = in;
  43.     }
  44.  
  45.     if (!pos){
  46.         return NULL;
  47.     }
  48.  
  49.     //printf("\tDEB:%d:%s\t%d:%s\n",strlen(pos),pos,strlen(separator),separator);
  50.     //printf("\tINFO:String ok:%s\n",pos);
  51.  
  52.     unsigned int i = 0;
  53.     while (i < strlen(pos)){
  54.         for (unsigned int j = 0;j < strlen(separator);j++){
  55.             //printf("\t%c == %c\n",pos[i],separator[j]);
  56.             if (pos[i] == separator[j]){
  57.                 ret = (char*)malloc(i+1);
  58.                 strncpy(ret,pos,i);
  59.                 ret[i] = '\0';
  60.                 //printf("\tINFO:copy string:%s\n",ret);
  61.                 char *tmp = (char*)malloc(strlen(pos) - i);
  62.                 strcpy(tmp,pos+i+1);
  63.                 //printf("\tINFO:copy temp:%s\n",tmp);
  64.                 if (pos) {
  65.                     free(pos);
  66.                 }
  67.                 pos = tmp;
  68.                 //printf("\tINFO:free pos\n");
  69.                 return ret;
  70.             }
  71.         }
  72.         //printf("\t~\n");
  73.         i++;
  74.     }
  75.  
  76.     char *tmp = (char*)malloc(strlen(pos)+1);
  77.     strcpy(tmp,pos);
  78.     if (pos){
  79.         free(pos);
  80.     }
  81.     pos = NULL;
  82.     return tmp;
  83.  
  84. }
Advertisement
Add Comment
Please, Sign In to add comment