【发布时间】:2019-08-06 05:17:48
【问题描述】:
我无法修复此功能以逐行反转文件中的单词。我不知道如何处理新行。这不是学校的任务,我只是想自己解决这个问题,我已经做了一段时间了。我收集到 '\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
提前谢谢你。
【问题讨论】:
-
您如何将输入从
main()传递给reverseWord?buffer包含完整的多行字符串? -
stephanie86 请通过minimal reproducible example回答上述评论中的问题。
-
@stephanie86 尝试更不规则的输入,例如
"abc 1\ndefhij klmnopq 2\nrst uvw xyz 3\n"。通过该输入,您可以发现逻辑中的更多缺陷。使用此输入,输出显示为"3\n xyz uvw 2\nrst klmnopq 1\ndefhij abc"。 -
请发布正确的minimal reproducible example,包括包含、输入、输出代码。