c - 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
先感谢您。
解决方案
首先:如果您在这里用像 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
. 但是您应该仔细调查换行符是否正确。您可能想学习为此使用调试器。
推荐阅读
- reactjs - 如何访问项目根目录之外的静态文件?
- asp.net-core - 应用程序总是在未经授权的控制器或操作上返回登录页面,而不是 401
- python - 如何从 mongodb 查询中获取字典而不是列表?
- python-3.x - 处理来自导入模块的记录器
- c# - 正则表达式使用嵌套的多部分数据字符串序列的各个部分获取 MatchCollection
- search - Netsuite 搜索选择自定义字段
- ios - 计时器不会快速停止
- c# - Saxon HE XQuery 进程节点在文档中抛出关于 BaseUri 的错误
- ios - OpenGL ES2:在顶点着色器(iOS)中使用“布局”关键字时出现语法错误
- azure - 在 Azure 逻辑应用中循环 SQL Server 表中的所有行