ここ初心者。渡す文字列のすべての単語が、定義した行のサイズよりも小さい場合、正常に機能する 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;
}