// https://forum.arduino.cc/t/text-justification-for-display/1404815
// 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8
// position: 0....5....0....5....0....5....0....5....0....5....0....5....0....5....0....5....0
char sentence[] = "The quick brown fox jumps over a lazy dog. Never gonna give you up! 0123456789";
/* 1 1 2 2
1...5....0....5....0.....6
The quick brown fox jumps[25 crlf]
over a lazy dogs. Never[48 crlf]
gonna give you up![67 crlf]
0123456789[77 crlf or nul]
*/
const int sentencelength = sizeof(sentence) / sizeof(sentence[0]);
const int chars[sentencelength];
int whitespaceDetected, whitespaceInside, characterwidth = 26, linenumber;
enum justification {left, right, center};
void setup() {
Serial.begin(115200);
align(left); // left, right, center, justify
}
void align(int just) {
for (int position = 0; position < sentencelength; position++) { // read sentence
if (sentence[position] == ' ') { // if the character is whitespace...
whitespaceDetected = position; // ... store this whitespace position
if ((position - (linenumber * characterwidth)) < characterwidth) { // ... and position is within width...
Serial.print(sentence[position]); // print the whitespace and...
whitespaceInside = position; // ... store this whitespace position
} else { // if whitespace is at or outside screen width...
linenumber++; // increase line for (x,y) screens
Serial.println(); // CRLF for serial monitor
for (int i = whitespaceInside + 1; i < position + 1; i++) { // print starting last whitespace to current index
Serial.print(sentence[i]); // reprint overlap word
}
}
} else if ((position - (linenumber * characterwidth)) < characterwidth) {
Serial.print(sentence[position]); // print non-whitespace character
}
}
}
void loop() {
}