Link to home
Start Free TrialLog in
Avatar of singhtaj
singhtaj

asked on

How do I seperate this ?

If I have a program where :
char *X= "Fri, 27 Feb 1998" ;

How would I access "Fri", "27", "Feb" "1998" individually ?
Given the fact I don't  know the number of blank spaces
between them ???

Any ideas ..
Any help will be appreciated.

Thanks
Avatar of elfie
elfie
Flag of Belgium image

You can use the strtok function and check for the length of the returned strings.
Avatar of singhtaj
singhtaj

ASKER

char *X="Fri, 27 Feb 1998";
char *wd = strtok(X," ,");
char *md = strtok(0," ,");
char *mon = strtok(0," ,");
char *year = strtok(0," ,");
printf("%s, %d %s %d\n",wd,atoi(md),mon,atoi(year));
Avatar of ozo
Well, actually strtok() serves as a tokenizer; a scan seems more appropriate here.
char *X="Fri, 27 Feb 1998";
char *wd = (char *)malloc(strlen(X));
char *mon = (char *)malloc(strlen(X));
int md,year;
sscanf(X,"%[^, ]%*c%d %s %d",wd,&md,mon,&year);
:)

But... shouldn't be:

char *wd = malloc(strlen(X) + 1);

(also, the typecast is discouraged if you are writing - and compiling - ANSI-C code, because fools the compiler; it is needed by C++)
Sorry. In my haste I neglected to #include <stdlib.h> or <malloc.h> to declare malloc,
and casting was the easiest way to get rid of the warnings.

I thought of strlen(X)+1 too, but figured as long as at least one other field matched...

Maybe strdup(X) would have been simpler.
you may use strtok() or you may write a small fnc as shown below.(please include stdio.h and malloc.h)
char *[] FormatDate(char *SrcDate){ static char *FormattedStrings[4];int i=j=k=len=0;
for(;SrcDate[i] && j<4;j++,k=i,len=0)
{ for(;SrcDate[i] && SrcDate[i]!=' ' && SrcDate[i]!=',';i++,len++);
FormattedStrings[j]=(char*)malloc(len+1);
strncpy(FormattedStrings[j],&SrcDate[k],len);}}
return FormattedStrings;}
/* the required format is stored in strings in a DD  cahr array */
ASKER CERTIFIED SOLUTION
Avatar of rsjetty
rsjetty

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
getting it to work may prove instructive;)