1

初学者在这里。我正在用 C 编写一个 wrap 函数,如果我传递的字符串中的所有单词都小于我定义的行的大小,则该函数可以正常工作。例如:如果我想在 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;
}
4

2 回答 2

0

您可能需要 malloc 一块内存并从您的字符串复制到新区域。当您到达要添加中断的位置时,只需插入换行符。请记住,需要释放新的内存块,否则您将发生内存泄漏并最终耗尽内存。

于 2012-11-14T17:43:09.093 回答
0

对于 realloc 问题,一个很好的解决方案是gap buffer

您最初在数据前面分配了 4Kb 间隙。

[____________string start here... ]  
[str____________ing start here... ]  
[string\n___________start here... ]   <-- here I just decided to insert line break

当您删除空格或字符时,差距会变得更大。当您添加连字符和换行符时,间隙会缩小。在任何情况下,您只需将每个角色从间隙的末端移动到间隙的开头一次。

可能的第一遍是在缓冲区的末尾插入间隙并向后工作以删除额外的空格或换行符,或者计算字长。

当然,如果下一个单词太长,可以随时向前看并计算。

于 2012-11-14T18:22:18.783 回答