0

Im new to C, and I would like to learn how can I Strack multiple words from a string just using strchr().. cant use strtok, scanf or similar functions..

I have string:

char myImput[51]="my flight to New Orleans, is at 12:30"

the string format is: "my flight cityname, is at hh:mm" i want to extract the cityname (it can have spaces) the hh and mm

is there a way to extra the cityname into a a new string called city, the hh to hour and mins to minutes?

I would like to:

printf("the flight to %s, is at %s hr and %s mins", cityname, hour, minutes);

I would really appreciate your help thank you in advance

JeanBook
  • 31
  • 7
  • Can you please proofread your post and edit as appropriate? I am not sure whether "strack", "extract" and "extra" are all supposed to be the same word. – Nate Eldredge Apr 06 '20 at 16:14

2 Answers2

0

In C, the strtok() function is used to split a string into a series of tokens based on a particular delimiter. and this is the syntax : char *strtok(char *str, const char *delim) so you can do simply like this :

 char myImput[51]="my flight to New Orleans, is at 12:30";
 // Extract the first token
 char * token = strtok(myImput, " ");
 // loop through the string to extract all other tokens
  while(token != NULL ) {
  printf( " %s\n", token ); //printing each token
  token = strtok(NULL, " ");
  }

Now it's for you to do the same for the time's token (which is the last token in your case). for more information check this link :

0

I have a proposition with strchr if you must use it :

    const char myImput[51]="my flight to New Orleans, is at 12:30";
    const char ch = ' ';//ch is the delimiter'an unsigned char)
    char *rst;//the string result after the first occurence of ch
    rst=strchr(myImput,ch) ;
     printf("String after |%c| is - |%s|\n", ch, rst) ;

     while(rst !=NULL)
     {
     printf("String after |%c| is - |%s|\n", ch, rst) ;
     rst=rst+1 ;
     rst = strchr(rst, ch);
     }

PS: I increment rst rst = rst + 1 because strchr return the first occurence of the delimiter whith the result, in your case for example it return" flight to New Orleans, is at 12:30 "with space in first of the string and that cause an infinite loop because it always find the first occuence is that space! i hope you undrestand me! it's your turn to do the same for the time.