beginner here. I'm writing a wrap function in C which is working OK if all the words from the string I pass are smaller than the size of the line I define. e.g.: if I want to wrap after 20 characters and pass a 21 characters word it doesn't wrap.

What I actually want to do is to add a hyphen at the end of the line if I pass a long word (longer than defined line size) and carry on on the next line.
I have researched and found a lot of websites with wrap functions, but none of them showed how to insert the hyphen, so could you guys help me out? Could you show me a example with inserting hyphens or point me on the right direction please?
Thanks in advance!

#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;
}

Thanks for your input. I understand you can't just go and break the word at the end of the line. I worked out how to break a long word, however the 'hyphen' and 'return' characters are replacing two characters of that long word. I know that using realloc would work but it wouldn't be very efficient if I input a very long string. So is there any other way you can think of? Thanks.
–
Mirko CroCopNov 14 '12 at 17:27

2 Answers
2

You probably need to malloc a block of memory and copy from your string into the new area. When you get to the place that you want to add the break, simply insert a newline. Remember that something needs to free the new block of memory or you will have a memory leak and eventually run out of memory.

As you delete spaces or characters, the gap gets wider. As you add hyphens and line breaks, the gap shrinks. In any case you have to concern only moving every character once from the end of the gap to the beginning of the gap.

A possible first pass would be to insert the gap at the end of the buffer and work backwards to delete extra spaces or line breaks and or to calculate word lengths.

Of course one can at any time look ahead and calculate if the next word is too long.