Advertisement
Guest User

Untitled

a guest
Nov 17th, 2017
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.83 KB | None | 0 0
  1. /* structure for a node */
  2. /*Hello Erik,
  3.  *
  4.  * Thanks a lot for your time today.Please find the exercise below.Take your time and show me your inner C skills;)
  5.  *
  6.  * # The split
  7.  *
  8.  * In C, write a function that takes into input :
  9.  * -a null terminated string
  10.  *  - a character
  11.  *  and returns an array of strings.
  12.  *
  13.  *  The array of strings will be the parts of the original string, separated by the character.
  14.  *
  15.  *  E.g.:
  16.  *
  17.  *  "qwe.try.cdsd”, ‘.' -> ["qwe", "try", "cdsd"]
  18.  *
  19.  *  Please let me know if anything was unclear!
  20.  *
  21.  *  Cheers,
  22.  *  */
  23.  
  24. /* strtok example */
  25.  
  26. /*Arbitrary number depending on the kind of input*/
  27. #include<stdio.h>
  28. #include<stdlib.h>
  29. #include<string.h>
  30.  
  31. #define size 10
  32.  
  33. char **split_str_lib(char *str, char *delimiter)
  34. {
  35.     int length = size;
  36.     char *temp_str;
  37.     memcpy(temp_str, str, strlen(str)*sizeof(char *));
  38.     char **array_strings = malloc(10*sizeof(char *));
  39.     int pos = 0;
  40.  
  41.     for (char *p = strtok(temp_str, delimiter); p; p = strtok(NULL, delimiter)){
  42.         array_strings[pos]= strdup(p);
  43.         pos++;
  44.         if(pos >=length){
  45.             length *=2;
  46.             array_strings = realloc(array_strings,length*sizeof(char *));
  47.         }
  48.     }
  49.  
  50.     array_strings[pos] = NULL;
  51.     return array_strings;
  52. }
  53.  
  54.  
  55. void print_array_strings(char **array_strings)
  56. {
  57.     for(int print = 0; array_strings[print]; print++){
  58.         printf("%s ", array_strings[print]);
  59.     }
  60. }
  61.  
  62.  
  63. int main()
  64. {
  65.     char str[] = "qwe.try.cdsd.qwe.try.cdsd.qwe.try.cdsd.qwe.try.cdsd.qwe.try.cdsd";
  66.     char del[] = ".";
  67.     char *pch;
  68.     /*printf ("Splitting string \"%s\" into tokens:\n", str);
  69.     pch = strtok (str,".");
  70.     while (pch != NULL){
  71.         printf ("%s\n",pch);
  72.         pch = strtok (NULL, " ,.-");
  73.         }*/
  74.     printf("string: %s\n", str);
  75.     char **array_strings = split_str_lib(str, del);
  76.     printf("string: %s\n", str);
  77.     print_array_strings(array_strings);
  78.     return 0;
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement