#include <stdio.h>
#include <string.h>
int length_prev_word(char *s) {
int i = 0;
while (*s != ' ') {
i++;
s++;
}
return i;
}
void cut_words(const char *text, int width) {
char *s = (char *)text;
int a, b, k;
char *e;
// skip leading spaces
while (*s && *s == ' ')
s++;
while (strlen(s) > width) {
// *s must be nonspace and not EOS
char *e = s + width - 1;
// *e is last char that can possibly fit
// *e cannot be EOS nor can e[1]
// back up to nonspace if at space
while (*e == ' ')
e--;
// *e is inside or end of word
if (e[1] != ' ') {
// not end of word; must be inside
// back up to prev space
while (e > s && *e != ' ')
e--;
// if e == s then no word break
// must assume word is longer than width
if (e == s)
e = s + width - 2;
else
// find end of prev word
while (e > s && *e == ' ')
e--;
}
// *e is end of word
k = e - s + 1;
b = (width - k) / 2;
a = (width - k) / 2 + (width - k) % 2;
if (length_prev_word(s) > width)
printf("* %*.*s%*.*s-%*.*s *\n", b, b, "", k, k, s, a-1, a-1, "");
else
printf("* %*.*s%*.*s%*.*s *\n", b, b, "", k, k, s, a, a, "");
s += k;
while (*s && *s == ' ')
s++;
}
if (*s) {
k = strlen(s);
b = (width - k) / 2;
a = (width - k) / 2 + (width - k) % 2;
printf("* %*.*s%*.*s%*.*s *\n", b, b, "", k, k, s, a, a, "");
}
}
void framed(const char *text, int width) {
int i;
for (i = 0; i < width; i++)
printf("*");
printf("\n");
cut_words(text, width - 4);
for (i = 0; i < width; i++)
printf("*");
}
int main() {
//const char text[]="This is word with four characters";
//int width = 20;
//const char text[] = "This word Thyroparathyroidectomized is too long for frame";
//int width = 20;
const char text[]="This word Thyroparathyroidectomized is too long for frame";
int width = 10;
framed(text, width);
return 0;
}