gpt4 book ai didi

c - 如何将字符串作为输入,然后在新行中打印每个单词

转载 作者:行者123 更新时间:2023-11-30 16:06:05 25 4
gpt4 key购买 nike

i want to to take a string as a input and then print each word in a new line.

Condition is: printed word must be stored in a array and every word will be removed from array after printing it.

#include<stdio.h>
int main() {
char s[100], tmp[20];
int i=0,space=0,k;
scanf("%[^\n]", s);

while(s[i]!='\0'){
if(space==0) tmp[i]=s[i]; //copying word only
else tmp[i-(k+1)]=s[i]; //copying word only

if((s[i]==' ')||(s[i+1]=='\0')){
tmp[i+1]='\0';
space++;
printf("%s\n", tmp); //printing word from an array

for(int j=0; tmp[j]!='\0'; j++) tmp[j]='\0'; //erasing this array for reuse
k=i++; //(i++) for skip space and 'k' for starting index from tmp[0]
if(s[i]=='\0') i--; //when null don't need to increase i for skip space
}
i++;
}
return 0;
}

谁能帮我理解这个问题?

最佳答案

这明显违反了您的条件,但该条件不合适,我认为读者值得了解如何在没有它的情况下做到这一点。这种方法的主要好处是您不会对输入长度施加任意限制。 (在原始代码中,输入不得超过 100 个字节。)我假设您的问题陈述只是实现 tr -s '[[:space:]]'\\n,您可以执行哪种情况:

#include <stdio.h>
#include <ctype.h>

/* Simple implementation of tr -s '[[:space:]]' \\n */

int
main(void)
{
int in_space = 0;
int c;
while( (c = getchar()) != EOF ) {
if(isspace(c)) {
if( !in_space )
putchar('\n');
in_space = 1;
} else {
in_space = 0;
putchar(c);
}
}
if(!in_space)
putchar('\n');
return 0;
}

可以稍微简化(IMO,上面的内容过于冗余):

#include <stdio.h>
#include <ctype.h>

/* Simple implementation of tr -s '[[:space:]]' \\n */

int
main(void)
{
int c;
int last = '\n';
while( (c = getchar()) != EOF ) {
c = isspace(c) ? '\n' : c;
if( c != '\n' || last != '\n' )
putchar(c);
last = c;
}
if( last != '\n' )
putchar(c);
return 0;
}

甚至:

#include <stdio.h>
#include <ctype.h>

/* Simple implementation of tr -s '[[:space:]]' \\n */

void
dedup(int c)
{
static int last = '\n';
if( c != '\n' || last != '\n' )
putchar(c);
last = c;
}

int
main(void)
{
int c;
while( (c = getchar()) != EOF ) {
dedup( isspace(c) ? '\n' : c);
}
dedup('\n');
return 0;
}

关于c - 如何将字符串作为输入,然后在新行中打印每个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60062674/

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