【问题标题】:c program for printing each word in string backwardsc程序用于向后打印字符串中的每个单词
【发布时间】:2014-04-19 10:13:11
【问题描述】:

这是我的源代码,用于向后打印字符串中的每个单词。但是这段代码只是向后打印第一个单词而不是整个字符串。在向后打印第一个单词后,它会生成向后打印的第一个和第二个单词的模式。如果使用 while 而不是 if 那么它会生成一个无限循环。

// Print an Entered String Backwards
#include <stdio.h>
#include <string.h>

int main()
{
    int j,i;
    char str[100];
    printf("Enter String\n");
    gets(str);
    printf("\nString in Reverse Order\n");
    i=0;
    while(str[i]!='\0')
    {
        if(str[i]==' ')
        {
            for(j=i-1;j>=0;j--)         //Loop starts from last char and decrements upto 0th char
                printf("%c",str[j]);
            printf(" ");
        }
        i++;
    }
}

【问题讨论】:

  • 整理出indetation。顺便说一句 - 这些讲师是否在他们给学生设置的问题上做得更好。 @userX - 学习使用调试器
  • 你的逻辑错了。用纸笔勾勒逻辑,手动测试,然后编写程序。
  • @user3551403 - WhozCraig(谢谢)为你修复了它
  • 我不明白描述...如果输入是'bar dog',你想要什么输出:'dog bar'或'rab god'或者可能是'god rab'...?
  • @CiaPan 我只想反转 d 个单词的字母但保留单词的顺序。 'bar dog' 的输出应该是 'rab god'

标签: c string infinite-loop


【解决方案1】:

不要使用gets。它不安全并且已被弃用。请改用fgets 来读取输入字符串stdin。现在,要向后打印字符串中的每个单词,您需要更改 while 循环。

#include <stdio.h>

int main(void)
{
    int i, j;
    char str[100];
    printf("Enter String\n");

    // fgets reads one less than sizeof(str), i.e., 99
    // characters from stdin and stores them in str array.
    // it returns when a newline is input which it stores in
    // the the array and then appends a terminating null byte
    // to mark the end of the string
    fgets(str, sizeof str, stdin);
    printf("\nString in Reverse Order\n");

    i = 0;
    while(str[i] != '\0')
    {
        if(str[i] == ' ' || str[i] == '\n')
        {   
            // the loop condition checks for either the 
            // start of the string or a whitespace since
            // since these two cases demarcate a word from
            // other words in the string
            for(j = i - 1; j >= 0 && str[j] != ' '; j--)
                printf("%c", str[j]);

            printf(" ");    
        }
        i++;
    }
    // output a newline to flush the output
    printf("\n"); 
    return 0;   
}

【讨论】:

  • gets 是不安全且不可取的,因为如果输入字符串太长,那么它会溢出缓冲区,导致未定义的行为,并且很可能由于段错误而导致程序崩溃。
  • @user3551403 但是,如果输入字符串足够小,可以存储在数组str 中,那么gets 可以工作,但您不应该这样做。
【解决方案2】:

每次您将内部循环测试为零时,每次都会打印到字符串的开头。您只需要测试直到找到最后一个空间。 像这样的内部循环

int lastSpace = 0, i = 0, j = 0;
while(str[i] != '\0')
{
if(str[i] == ' ')
{
for(j = i-i; j>= lastSpace; j++)
{
   printf("%c", str[j]);
}
lastSpace = i;
}
i++;
}

【讨论】:

  • 这以j=i-i == 0 开头。所以它从第一个字符开始,然后继续向下进入某种堆空间。这个会很有趣:)
  • @ssm 但它没有生成我想要的输出! :)
  • 只需将j=i-i 转换为j=i :)
【解决方案3】:

无需双循环,单循环即可。

#include<stdio.h>
#include<string.h>

int main()
{
    int j,i, len;
    char str[100];
    clrscr();
    printf("Enter String\n");
    gets(str);
    printf("\nString in Reverse Order\n");
    i = strlen(str) - 1;
    while(i > -1)
    {
    printf("%c",str[i--]);
    }
}

【讨论】:

  • 这只是颠倒整个字符串(这意味着颠倒了单词 的顺序)。我相信(也许我错了)目标是颠倒单词但保留它们的顺序。
  • @Pawan kumar 我希望订单保持不变。
  • 喜欢“狗吠”“神蟹”或“狗吠”“后备狗”
  • 上帝应该是:)
  • 我发布了另一个答案检查这个。
【解决方案4】:

您评论的循环不应在第 0 个字符处结束,而应到达最后一个空格(如果有的话)。

//Print an Entered String Backwards
#include<stdio.h>
#include<string.h>

int main()
{
    int j,i; int lastWhiteSpace = 0; //there were no white spaces
    char str[100];

    printf("Enter String\n");

    gets(str);

    printf("\nString in Reverse Order\n");

    i=0;
    while(str[i]!='\0')
    {
        if(str[i]==' ')
        {
            for(j=i-1;j>=lastWhiteSpace;j--)  //Loop starts from last char and decrements upto the character after the last white space 
                printf("%c",str[j]);
            printf(" ");
            lastWhiteSpace = i + 1; //the character after this white space 
        }
        i++;
    }

    //later edit
    for(j=i-1;j>=lastWhiteSpace;j--)
        printf("%c",str[j]);
    printf("\n");
}

【讨论】:

  • 那么限制条件4循环应该是什么?
  • 您还应该在循环之前初始化lastWhitespace。如果句子以很多空格开头怎么办。
  • @Scooby 这段代码最多只能使用几个单词,而不是字符串中的所有单词。
  • 因为字符串中只有 100 个字符?它不应该只对最后一个词起作用,因为它需要单独处理。
  • 为什么最后一个字需要分开处理?
【解决方案5】:
#include<stdio.h>
#include<string.h>

int main()
{
    int j,i, len;
    char str[100];
    char temp[20];
    clrscr();
    printf("Enter String\n");
    gets(str);
    printf("\nString in Reverse Order\n");
    i = 0;
    len = 0;
    j = 0;
    while(str[i] != '\0')
    {
        if(str[i] != ' ')
            temp[j++] = str[i];

        if(str[i] == ' ')
        {
            temp[j] = '\0';
            len = strlen(temp);

            while(len > -1)
            {
                printf("%c", temp[len--]);
            }
            printf(" ");
            len = 0;
            j = 0;
        }
    i++;
    }
    temp[j] = '\0';
    len = strlen(temp);
    printf(" ");
    while(len > -1)
    {
        printf("%c",temp[len--]);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-14
    • 2019-06-28
    • 1970-01-01
    • 1970-01-01
    • 2015-04-21
    • 1970-01-01
    相关资源
    最近更新 更多