首页 > 解决方案 > C程序用新行反转字符串

问题描述

我无法修复此功能以逐行反转文件中的单词。我无法弄清楚如何处理新行。这不是学校的作业,我只是想自己解决这个问题,我已经做了一段时间了。我收集到 '\n' 字符附加到单词的末尾,算法没有考虑到这一点,我不知道怎么做。您能告诉我如何正确实施吗?

void reverseWord (char* buffer, int size) 
{ 
    char* start = buffer; 

    // bounds 
    char* temp = buffer; 

    // Reversing the words
    while (*temp) { 
        temp++; 
        if(*temp == '\n'){
            temp++;
        }
        if (*temp == '\0') { 
            reverse(start, temp - 1); 
        } 
        else if (*temp == ' ') { 
            reverse(start, temp - 1); 
            start = temp + 1; 
        } 
    } 

    // Reverse the entire string 
    reverse(buffer, temp - 1); 
} 




void reverse(char* begin, char* end) 
{ 
    char temp; 
    while (begin < end) { 
    temp = *begin; 
    *begin++ = *end; 
    *end-- = temp; 
    } 
}

我的输入文件是:

    this is line 1
    this is line 2
    this is line 3
    this is line 4
    this is line 5

我想要的输出是:

    5 line is this
    4 line is this
    3 line is this
    2 line is this
    1 line is this

我的实际输出是这样的:

    5
     line is this4
     line is this3
     line is this2
     line is this1

先感谢您。

标签: cfunctionreverse

解决方案


首先:如果您在这里用像 C 这样的“简单”语言发布问题,请提供像 @Yunnosch 所说的最小可重现示例。它会让你有更多的人尝试你的代码。

如果它是原始的就足够了

int main() {
  char buffer[] =
    "this is line 1\n"
    "this is line 2\n"
    "this is line 3\n"
    "this is line 4\n"
    "this is line 5\n";
  printf("%s", buffer);
  reverseWord(buffer, strlen(buffer));
  printf("%s", buffer);
}

顺便说一句,我从您未修改的代码中得到的输出与您发布的有点不同:

5
 line is 4
this line is 3
this line is 2
this line is 1
this line is this

好吧,现在到你的代码。

您的while-loop 永远不会评估if (*temp == '\0')为,true因为它的条件会事先中断循环。但这不是原因。

您可以像查看任何其他空白字符一样查看换行符。所以我成功地尝试了这个:

while (*temp) {
    temp++;
    if (isspace(*temp)) {
        reverse(start, temp - 1);
        start = temp + 1;
    }
}

你需要#include <ctype.h>isspace().

它似乎甚至适用于 Windows 风格的换行符,如\r\n. 但是您应该仔细调查换行符是否正确。您可能想学习为此使用调试器。


推荐阅读