c - Parsing string into dynamic array with specific delimiters -
i have code parsing string dynamic array need help figuring out how specific delimiters user inputs string, illustration "abc dfg $opq&some new words" , need parse array. $
, &
signs nowadays in strings move place place. need parse parse string ("abc dfg $opq&some new words") way
array[0] = abc array[1] = dgf array[2] = ops array[3] = new words
the &
sign telling me origin of kind of sentence need store in array.
my output is
abc dfg $opq&some new words subrcmd[0] = abc subrcmd[1] = dfg subrcmd[2] = opq&some subrcmd[3] = new words subrcmd[4] = (null)
my code
#include <stdio.h> #include <string.h> #include <stdbool.h> #include <stdlib.h> int count=0; char* parse_str ( char **cmd, char input[]);//function parse string int main(int argc, const char * argv[]) { char input[20]={0}; char c = '\0'; char ** cmd = null;//create pointer , set null char *p; char *ptr1; while (strcmp(input, "exit") != 0)//check if exit typed cmd line, if exit { scanf("%50[^\n]", input);//scan user input cmd line p=strchr(input, '&');//check if user input contains & if (p) { ptr1 = parse_str(&ptr1, input);//if parse string } while((c = getchar()) != '\n' && c != eof); //flush buffer } free(ptr1);//free memory homecoming 0; } char* parse_str ( char **cmd, char input[])//function parse string { int size=0; char *ptr = strtok (input, " $");//parse string based on space or $ sign cmd = malloc(sizeof(char));//allocate memory dynamic array while (ptr)//split string tokens " " { cmd = realloc (cmd, sizeof(char*)*(++size));//realloate memory if needed if (cmd == null) exit (-1); // memory allocation failed cmd[size-1] = ptr; ptr = strtok (null, " $"); count++;//count words in input if (strchr (ptr, '&'))//search & sign in word, if it's there parse rest of string based on \n or & { while (ptr) { cmd = realloc (cmd, sizeof(char*)*(++size));//reallocate more memory array if (cmd == null) exit (-1); // memory allocation failed cmd[size-1] = ptr; ptr = strtok(null, "&\n");//look end of line or & sign count++;//increment word count } } } cmd = realloc (cmd, sizeof(char*)*(size+1));// realloc 1 element lastly null cmd[size] = 0; int i; (i = 0; < (size+1); ++i) printf ("subrcmd[%d] = %s\n", i, cmd[i]); homecoming *cmd; }
c string
No comments:
Post a Comment