我想打印输入字符串中以空格分隔的单词

时间:2019-09-22 18:37:37

标签: c arrays string while-loop

l该代码中有问题,当它进入内部while循环时它将停止工作,它应该已经打印了单个单词。例如,字符串为“我的名字是杰克”,输出应为 我的名字叫杰克,换行后的每个单词

int main (void)
{
int i=0,j=0;
char paragraph[1000],word[100];
printf("Enter the paragraph:\n");
gets(paragraph);

while(paragraph[i]!='\0')
{
    int res = isspace(paragraph[i]);
    if (res != 0)
    {
        word[i]='\0';
        printf("\n");
        j=0;
        while(word[j] !='\0')
        {
            printf("%s",word[j]);
            j++;
        }
        j=0;
    }
    word[j] = paragraph[i];
    i++;
    j++;
}
return 0;
}

1 个答案:

答案 0 :(得分:-1)

#include <stdio.h>
#include <string.h>
int main()
{
    char str1[100];
    char newString[10][10]; 
    int i,j,ctr;
       printf("\n\n Split string by space into words :\n");
       printf("---------------------------------------\n");    

    printf(" Input  a string : ");
    fgets(str1, sizeof str1, stdin);    

    j=0; ctr=0;
    for(i=0;i<=(strlen(str1));i++)
    {
        // if space or NULL found, assign NULL into newString[ctr]
        if(str1[i]==' '||str1[i]=='\0')
        {
            newString[ctr][j]='\0';
            ctr++;  //for next word
            j=0;    //for next word, init index to 0
        }
        else
        {
            newString[ctr][j]=str1[i];
            j++;
        }
    }
    printf("\n Strings or words after split by space are :\n");
    for(i=0;i < ctr;i++)
        printf(" %s\n",newString[i]);
    return 0;
}