初學者在這裏。我正在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;
}
感謝您的輸入。我知道你不能在這一行結尾打破這個詞。我研究瞭如何打破一個長詞,然而'連字符'和'返回'字符正在替代那個長詞的兩個字符。我知道使用realloc可以工作,但如果我輸入一個非常長的字符串,效率不會很高。那麼還有其他方式可以想到嗎?謝謝。 –