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