简体   繁体   English

倒序字中的最后一个字 function

[英]Last word in reverse word function

i have this reverse word function.我有这个反向词 function。 it simply adding word to new string in reverse order.它只是以相反的顺序将单词添加到新字符串中。 the problem with this code is it not print the last word ( first word before reverse ).这段代码的问题是它不打印最后一个单词(reverse 之前的第一个单词)。 i dont know why.我不知道为什么。 please help fix my code请帮助修复我的代码

    char str[100], revstr[100];
    int i, j, index, len, startIndex, endIndex;
    printf("\n Please Enter any String :  ");
    gets(str);

    len = strlen(str);
    index = 0;
    endIndex = len - 1;

    printf("\n *****  Given String in Reverse Order  ***** \n");        
    for(i = len - 1; i > 0; i--)
    {
        if(str[i] == ' ')
        {
            startIndex = i + 1;

            for(j = startIndex; j <= endIndex; j++)
            {
                revstr[index] = str[j];
                index++;
            }
            revstr[index++] = ' ';
            endIndex = i - 1;               
        } 
    }

    printf("\n Given String in Reverse Order = %s", revstr); 
    return 0;

Here's a working code:这是一个工作代码:

    char str[100], revstr[100];
    int i, j, index, len, startIndex, endIndex;
    printf("\n Please Enter any String :  ");
    gets(str);
    len = strlen(str);
    index = 0;
    endIndex = len - 1;

    printf("\n *****  Given String in Reverse Order  ***** \n");        
    for(i = len - 1; i >= -1; i--)
    {
        if(i == -1){
            startIndex = i + 1;

            for(j = startIndex; j <= endIndex; j++)
            {
                revstr[index] = str[j];
                index++;
            }
            revstr[index++] = ' ';
            endIndex = i - 1;  
            break;
        }
        if(str[i] == ' ')
        {
            startIndex = i + 1;

            for(j = startIndex; j <= endIndex; j++)
            {
                revstr[index] = str[j];
                index++;
            }
            revstr[index++] = ' ';
            endIndex = i - 1;               
        } 
    }

    printf("\n Given String in Reverse Order = %s", revstr); 

The problem was that you were only including a word if there was a space before it.问题是你只包含一个单词,如果它之前有一个空格。 There will be no space before the first word therefore I made the code go before the first letter and always include the first word forcefully.第一个单词之前没有空格,因此我在第一个字母之前设置了代码 go,并且始终强制包含第一个单词。 This code can be broken if there are more spaces than needed in the text.如果文本中的空格比需要的多,则此代码可能会被破坏。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM