Advertisement
Guest User

Untitled

a guest
Nov 17th, 2017
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.72 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 = 10;
  36.     char **array_strings = malloc(10*sizeof(char *));
  37.     int pos = 0;
  38.  
  39.     for (char *p = strtok(str, delimiter); p; p = strtok(NULL, delimiter)){
  40.         array_strings[pos]= strdup(p);
  41.         pos++;
  42.         if(pos >=length){
  43.             length *=2;
  44.             array_strings = realloc(array_strings,length*sizeof(char *));
  45.         }
  46.     }
  47.  
  48.     array_strings[pos] = NULL;
  49.     return array_strings;
  50. }
  51.  
  52.  
  53. void print_array_strings(char **array_strings)
  54. {
  55.     for(int print = 0; array_strings[print]; print++){
  56.         printf("%s ", array_strings[print]);
  57.     }
  58. }
  59.  
  60.  
  61. int main()
  62. {
  63.     char str[] = "qwe.try.cdsd.qwe.try.cdsd.qwe.try.cdsd.qwe.try.cdsd.qwe.try.cdsd";
  64.     char del[] = ".";
  65.     char *pch;
  66.     /*printf ("Splitting string \"%s\" into tokens:\n", str);
  67.     pch = strtok (str,".");
  68.     while (pch != NULL){
  69.         printf ("%s\n",pch);
  70.         pch = strtok (NULL, " ,.-");
  71.         }*/
  72.     printf("string: %s\n", str);
  73.     char **array_strings = split_str_lib(str, del);
  74.     print_array_strings(array_strings);
  75.     return 0;
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement