gpt4 book ai didi

c - 如何使字符串单词明智(以便以后我可以反转它们)存储在数组中?在 C

转载 作者:太空宇宙 更新时间:2023-11-04 03:06:36 25 4
gpt4 key购买 nike

我的代码是这样的!!

int i=0,j=0,k=0;
char *a[20];
int count=0;
for(i=0;i<20;i++)
{
a[i] = malloc(50 * sizeof(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 ");
}
}

最佳答案

“比 strtok & Co 更好”,见下文:

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;
}

更好,因为字符串可以是const,它在多线程中工作,空工作不会被忽略。

关于c - 如何使字符串单词明智(以便以后我可以反转它们)存储在数组中?在 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4236737/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com