gpt4 book ai didi

将空格转换为制表符

转载 作者:太空宇宙 更新时间:2023-11-04 05:46:14 24 4
gpt4 key购买 nike

我最近决定学习 C,所以我开始学习 K&R,但我在第 1 章的问题 21 上卡住了。你应该编写一个程序,给定一个没有制表符和特定制表符宽度的字符串,将所有白色转换为白色使用制表符和空格将空格转换为等效间距。

到目前为止,我得到了这个:

void entab (char from[], char to[], int length, int tabwidth)
{
int i, j, tabpos, flag, count;

j = tabpos = flag = count = 0;
for (i = 0; from[i] != '\0' && j < length - count - 2; i++) {
if (from[i] == ' ') {
// If you see a space, set flag to true and increment the
// whitespace counter. Don't add any characters until you reach the
// next tabstop.
count++;
tabpos = (tabpos + 1) % tabwidth;
flag = 1;
if (count >= tabwidth - tabpos) {
to[j] = '\t';
j++;
count = count - tabwidth + tabpos;
tabpos = 0;
}
} else {
if (flag == 1) {
// if you see something other than a space and flag is true,
// there weren't enough spaces to reach a tabstop. Add count
// spaces to the string.
flag = 0;
tabpos = (tabpos + count + 1) % tabwidth;
while (count > 0) {
to[j] = ' ';
j++;
count--;
}
} else {
tabpos = (tabpos + 1) % tabwidth;
}
count = 0;
to[j] = from[i];
j++;
}
}
to[j] = '\0';
return;
}

不幸的是,这似乎产生了比预期稍大的间距。关于我搞砸的地方有什么想法吗?

PS 我看过其他在线解决方案,我知道有更好的方法来解决这个问题,但我真的很想修复我的错误。

编辑:设置 tabwidth=4 并使用:

    foobar
foo bar foo bar
foo bar

作为输入,我得到:

/t/tfoobar
/t/t/t/tfoo bar/t/t/t foo bar
/t/tfoo/t/t bar

作为输出,而正确的输出是:

/tfoobar
/t/tfoo/t bar/t/t foo bar
/tfoo/t/tbar

最佳答案

单个函数中的这么多代码和这么多嵌套(四层深)很难正确处理,更难维护。

我建议您首先重构您拥有的内容,使其成为更易于管理的部分。例如:

  • 创建一个名为 findTab 的函数,该函数接受要测试的字符串、制表符宽度(空格数)并返回第一次出现的制表符的索引。
  • 然后创建一个名为 replaceChars 的函数,它获取 args 的权利并执行替换

这些只是一些想法。您最终会得到一些更短且更易于管理的函数,并且很可能会在此过程中发现您的错误!

顺便说一句,我尝试在 Google 上快速搜索一些 C 重构文章,但遗憾的是空手而归。如今,重构全都与 OOP 语言有关,例如 Java、C# 和 C++。不过,一些经验法则对您大有帮助:

  • 尽量减少代码块的嵌套:if 语句和for & while 循环
  • 尽量减少每个函数的行数(在合理范围内)使其少于 60 行
  • (借自 OOP 类)确保每个函数都很好地完成一件非常有限的事情
  • 更详细地命名您的变量和方法 - 这样做时似乎很痛苦,但它会在未来带来好处,就像现在一样。

祝你好运,欢迎来到 SO!

关于将空格转换为制表符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4504893/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com