初学者在这里。我正在C中编写一个包装函数,如果我传递的字符串中的所有单词都小于我定义的行的大小,则该函数正常工作。例如:如果我想在20个字符后换行并传递一个21个字符的单词则不会换行。
我实际想要做的是如果我传递一个长字(长于定义的行大小)并在下一行继续,则在行尾添加一个连字符。我已经研究并发现了很多带有包装功能的网站,但是没有一个显示如何插入连字符,所以你们可以帮帮我吗?你能告诉我一个插入连字符的例子或指向正确的方向吗?提前致谢!
我的包装功能:
int wordwrap(char **string, int linesize)
{
char *head = *string;
char *buffer = malloc(strlen(head) + 1);
int offset = linesize;
int lastspace = 0;
int pos = 0;
while(head[pos] != '\0')
{
if(head[pos] == ' ')
{
lastspace = pos;
}
buffer[pos] = head[pos];
pos++;
if(pos == linesize)
{
if(lastspace != 0)
{
buffer[lastspace] = '\n';
linesize = lastspace + offset;
lastspace = 0;
}
else
{
//insert hyphen here?
}
}
}
*string = buffer;
return;
}
我的主要功能:
#include <stdio.h>
#include <string.h>
int main(void)
{
char *text = strdup("Hello there, this is a really long string and I do not like it. So please wrap it at 20 characters and do not forget to insert hyphen when appropriate.");
wordwrap(&text, 20);
printf("\nThis is my modified string:\n'%s'\n", text);
return 0;
}
您可能需要malloc一块内存并从您的字符串复制到新区域。当您到达要添加中断的位置时,只需插入换行符即可。请记住,某些东西需要释放新的内存块,否则您将发生内存泄漏并最终耗尽内存。
对于realloc问题,一个很好的解决方案是间隙缓冲区。
你原先在数据前面分配说4Kb间隙。
[____________string start here... ]
[str____________ing start here... ]
[string\n___________start here... ] <-- here I just decided to insert line break
删除空格或字符时,差距会变宽。当您添加连字符和换行符时,间隙会缩小。无论如何,你只需要关注每个角色从间隙的末尾到间隙的开始移动一次。
可能的第一遍是在缓冲区的末尾插入间隙并向后工作以删除额外的空格或换行符和/或计算字长。
当然,人们可以在任何时候向前看,并计算下一个单词是否太长。