c - 将连字符插入 wrap 函数

标签 c function word-wrap

这里是初学者。我正在用 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 一 block 内存并将您的字符串复制到新区域。当您到达要添加分隔符的位置时,只需插入一个换行符即可。请记住,某些东西需要释放新的内存块,否则您将发生内存泄漏并最终耗尽内存。

关于c - 将连字符插入 wrap 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13381827/

相关文章:

html - CSS,自动换行

c++ - Win32 API 函数与它们的 CRT 对应函数(例如 CopyMemory 与 memcpy)

html - Span 文本换行与第一行对齐

c++ - 未定义、未指定和实现定义的行为

c - C如何知道函数中二维动态数组的维度?

javascript - 带有参数的函数值的 JSON

python - 为什么类中函数名和变量名不能叫同一个?

c# - 如何从多行文本框中获取换行?

c - 查找矩阵 NxN 中的所有峰值

将字符串用户输入转换为 double