开发者

how to make a string word wise(so that later i can reverse them ) store in array?? in C

开发者 https://www.devze.com 2023-01-26 17:35 出处:网络
my code goes like this !! int i=0,j=0,k=0; char *a[20]; int count=0; for(i=0;i<20;i++) { a[i] = malloc(50 * sizeo开发者_运维知识库f(char));

my code goes like this !!

int i=0,j=0,k=0;
 char *a[20];
 int count=0;
 for(i=0;i<20;i++)
    {
       a[i] = malloc(50 * sizeo开发者_运维知识库f(char));
    }
   i=0; 
 while(*(p+i)!='\n')
 {
  int k=0; 
   while(*(p+i)!=' ')
     {
    *(a[j]+k)=*(p+i);
    i++;
    k++;
   }
   *(a[j]+k)='\0';
                 i++;
          j++;
 }
 printf("\n Count%d",j);
 count=j;
 for(j=0;j<count;j++)
 {
  printf("%s",a[j]);
    printf("\n \n ");
  }
}  


'Better' than strtok & Co see below:

int strsplit(const char *s,char ***l,char t)
{
  int r=0;
  while( strchr(s,t) )
  {
    *l=realloc(*l,++r*sizeof*l);
    memcpy((*l)[r-1]=calloc(1,strchr(s,t)-s+1),s,strchr(s,t)-s);
    s=strchr(s,t)+1;
  }
  *l=realloc(*l,++r*sizeof*l);
  memcpy((*l)[r-1]=calloc(1,strlen(s)+1),s,strlen(s));
  return r;
}

int main()
{
    char **l=0,*x="1;2;;4";
    int i,r=strsplit(x,&l,';');
    for(i=0;i<r;++i)
    {
      puts(l[i]);
      free(l[i]);
    }
    free(l);
    return 0;
}

better because the string can be const, it work in multithreads, empty works are not be ignored.


You don't say whether or not your code actually works. Is there a problem or are you just asking for comments on your code? Your code will fail if there is any word longer than 49 characters.

You might instead use the library function strtok() to break up a string into tokens/words.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号