如果线宽设置为 80,并且第 80 个字符位于单词的中间,则整个单词必须放在下一行。因此,在您扫描时,您必须记住最后一个不超过 80 个字符的单词的结尾位置。
所以这是我的,不干净;在过去的一个小时里,我一直在努力让它工作,在这里和那里添加一些东西。它适用于我所知道的所有边缘情况。
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int isDelim(char c){
switch(c){
case '\0':
case '\t':
case ' ' :
return 1;
break; /* As a matter of style, put the 'break' anyway even if there is a return above it.*/
default:
return 0;
}
}
int printLine(const char * start, const char * end){
const char * p = start;
while ( p <= end )
putchar(*p++);
putchar('\n');
}
int main ( int argc , char ** argv ) {
if( argc <= 2 )
exit(1);
char * start = argv[1];
char * lastChar = argv[1];
char * current = argv[1];
int wrapLength = atoi(argv[2]);
int chars = 1;
while( *current != '\0' ){
while( chars <= wrapLength ){
while ( !isDelim( *current ) ) ++current, ++chars;
if( chars <= wrapLength){
if(*current == '\0'){
puts(start);
return 0;
}
lastChar = current-1;
current++,chars++;
}
}
if( lastChar == start )
lastChar = current-1;
printLine(start,lastChar);
current = lastChar + 1;
while(isDelim(*current)){
if( *current == '\0')
return 0;
else
++current;
}
start = current;
lastChar = current;
chars = 1;
}
return 0;
}
所以基本上,我想将start 和lastChar 设置为行的开头和行的最后一个字符。设置好后,我将所有字符从头到尾输出到标准输出,然后输出'\n',然后继续下一行。
最初一切都指向开始,然后我跳过带有while(!isDelim(*current)) ++current,++chars; 的单词。当我这样做时,我记得最后一个字符在 80 个字符之前 (lastChar)。
如果在一个单词的末尾,我已经传递了我的字符数 (80),那么我就会退出 while(chars <= wrapLength) 块。我输出start 和lastChar 和newline 之间的所有字符。
然后我将current 设置为lastChar+1 并跳过分隔符(如果这导致我到达字符串的末尾,我们就完成了,return 0)。将start、lastChar 和current 设置为下一行的开头。
if(*current == '\0'){
puts(start);
return 0;
}
part 用于太短而无法包装一次的字符串。我在写这篇文章之前添加了这个,因为我尝试了一个短字符串但它不起作用。
我觉得这可能以更优雅的方式可行。如果有人有什么建议,我很乐意尝试。
当我写这篇文章时,我问自己“如果我有一个比我的 wraplength 长的单词的字符串会发生什么” 好吧,它不起作用。所以我添加了
if( lastChar == start )
lastChar = current-1;
在printLine() 语句之前(如果lastChar 没有移动,那么我们有一个单词对于单行来说太长了,所以我们只需要把整个东西放在一行上)。
自从我写这篇文章以来,我就从代码中删除了 cmets,但我真的觉得肯定有比我不需要 cmets 的更好的方法来做到这一点。
这就是我如何写这个东西的故事。我希望它可以对人们有用,我也希望有人对我的代码不满意,并提出一种更优雅的方式。
需要注意的是,它适用于所有边缘情况:单词对于一行来说太长,字符串短于一个 wrapLength,以及空字符串。