Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* structure for a node */
- /*Hello Erik,
- *
- * Thanks a lot for your time today.Please find the exercise below.Take your time and show me your inner C skills;)
- *
- * # The split
- *
- * In C, write a function that takes into input :
- * -a null terminated string
- * - a character
- * and returns an array of strings.
- *
- * The array of strings will be the parts of the original string, separated by the character.
- *
- * E.g.:
- *
- * "qwe.try.cdsd”, ‘.' -> ["qwe", "try", "cdsd"]
- *
- * Please let me know if anything was unclear!
- *
- * Cheers,
- * */
- /* strtok example */
- /*Arbitrary number depending on the kind of input*/
- #include<stdio.h>
- #include<stdlib.h>
- #include<string.h>
- #define size 10
- char **split_str_lib(char *str, char *delimiter)
- {
- int length = size;
- char *temp_str;
- memcpy(temp_str, str, strlen(str)*sizeof(char *));
- char **array_strings = malloc(10*sizeof(char *));
- int pos = 0;
- for (char *p = strtok(temp_str, delimiter); p; p = strtok(NULL, delimiter)){
- array_strings[pos]= strdup(p);
- pos++;
- if(pos >=length){
- length *=2;
- array_strings = realloc(array_strings,length*sizeof(char *));
- }
- }
- array_strings[pos] = NULL;
- return array_strings;
- }
- void print_array_strings(char **array_strings)
- {
- for(int print = 0; array_strings[print]; print++){
- printf("%s ", array_strings[print]);
- }
- }
- int main()
- {
- char str[] = "qwe.try.cdsd.qwe.try.cdsd.qwe.try.cdsd.qwe.try.cdsd.qwe.try.cdsd";
- char del[] = ".";
- char *pch;
- /*printf ("Splitting string \"%s\" into tokens:\n", str);
- pch = strtok (str,".");
- while (pch != NULL){
- printf ("%s\n",pch);
- pch = strtok (NULL, " ,.-");
- }*/
- printf("string: %s\n", str);
- char **array_strings = split_str_lib(str, del);
- printf("string: %s\n", str);
- print_array_strings(array_strings);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement