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

标签 c arrays string while-loop

这段代码有问题,当它进入内部 while 循环时它停止工作,它应该打印单个单词。例如,字符串是“My name is jack”,输出应该是 我的名字是 jack ,换行后的每个单词

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

最佳答案

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

关于c - 我想打印输入字符串中以空格分隔的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58052339/

相关文章:

java - 这段检查数字是否为质数的代码有什么问题?

c++ - 从 std::string 解析两个或一个数字

java - JNI 无法在 NetBeans 上检测到 __int64

C打印 double 类型指针值不起作用

php - 值未通过 ajax 将 session 数组更新为 json 数组

javascript - 使用 Webpack 将模板字符串写入 .html 文件

linux - 尝试在 bash 中分割一个大字符串

c - 变量声明上的函数

c - 使用指针写入 strend(s, t)(检查 `s` 是否以 `t` 结尾)

C(Linux): warning: assignment discards qualifiers from pointer target type