这里是初学者。我正在用 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/