gpt4 book ai didi

c - 在单词之间拆分字符串并插入换行符

转载 作者:行者123 更新时间:2023-11-30 21:31:41 24 4
gpt4 key购买 nike

我有一个由几个句子组成的字符串。例如:

 hello world bye bye

现在,我需要将这句话变成一个单词:

hello
world
bye
bye

我有这个想法,但我不知道如何正确编写它,所以我希望你们能帮助我。这是我到目前为止所拥有的:

int len=0, k=0, stopatspace=0;
char temptext[100][15]={0};
char line[300]={0};

len=strlen(line);
printf("len is: %d", len);
for(k=0; k<len; k++)
{
if (k == ' ')
{
// i dont know what to write here in order to make it a cloumn
}
}

基本上,我的想法是在我的行的所有长度上运行,当我到达一个空间时,我希望它进入(向下一行,这样它看起来像一个库)

最佳答案

假设 line 是包含 hello world bye byechar 数组,并且 text 声明为

char text[100][15]; //I used 100 and 15 because your example contains it

并且您希望将每个单词复制到文本的每一行中。然后,使用strtok()函数以 ""(space) 作为分隔符,并将其放入一个循环中,当 strtok() 返回 NULL 时终止以获取每个单词。使用 strcpy() 将每个单词复制到 text 的每一行在循环中。

其代码如下所示:

char text[100][15];
char line[]="hello world bye bye";
int i=0;

char *token=strtok(line," ");

while(token!=NULL)
{
strcpy(text[i],token);
i++;
token=strtok(NULL," ");
}

现在,要打印它,您可以使用

for(int j=0;j<i;j++)
printf("text[%d]=%s",j,text[j]);

<小时/>另一种方法是手动复制每个字符,直到看到空格。

int len=strlen(line);
int i=0;
int k=0;

for(int j=0;j<len+1;j++)
{
if(line[j]==' ')
{
text[i][k]='\0';
i++;
k=0;
}
else
{
text[i][k]=line[j];
k++;
}
}

请注意,上面的代码不会阻止buffer overflows 。您可以使用打印每个单词

for(int j=0;j<i+1;j++)
printf("text[%d]=%s",j,text[j]);

关于c - 在单词之间拆分字符串并插入换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27939074/

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