Hi all,
The following code separates the words in a string so that if the character count on a line goes over 30, then it will move to the next line while keeping the word intact.
However, I can't figure out why its printing additional letters at the end of the string. What I have figured out, is that the number of unwanted characters it prints at the end, is the same as the number of lines that precede it. E.g. if 6 lines are printed, the 7th line will have 6 unwanted characters on it. I have no idea where these characters are coming from.
Here's the code:
const int length = 250; // The longest character length of any thought that will be passed through the program.
char thoughtStr[length] = "This is an example sentance that the string could contain, and the number of lines seems to match the number of unwated letters that are written at the end.";
byte numChar = 0; // Points to the character value in that element
byte numCharThought = 0; // Points to the element number in that thought
byte numCharPrinted = 0; // Points to the element number in that line
const byte paperWidth = 30; // Number of characters that can be printed per line.
byte endOfLastWord = 0;
byte endOfLastLine = 0;
byte newLineStr[15];
byte count = 0;
byte lastLineNum = 0;
byte lastCharNum = 0;
byte readyForNextLine = 0;
void setup() {
Serial.begin(9600);
printThought();
}
void loop() {
}
void printThought() {
for (int i = 0; i < length; i++) { // For the length of this thought:
// Determine where line breaks will occur
if (thoughtStr[i] == ' ' || thoughtStr[i] == '.') { // If the character is not a space or empty
readyForNextLine = newLineStr[count] + paperWidth;
if (i >= readyForNextLine || thoughtStr[i] == '.') { // If the current thought element is greater than 30 (0 to 30 is 31 characters. So 30 characters + the space or period.)
if (i >= readyForNextLine) {
count++;
newLineStr[count] = endOfLastWord + 1;
endOfLastWord = i - 1;
} else if (thoughtStr[i] == '.') {
count++;
lastLineNum = count;
lastCharNum = i;
endOfLastWord = i - 1;
newLineStr[count] = endOfLastWord + 1;
}
} else {
endOfLastWord = i - 1;
}
// Print the lines
if (thoughtStr[i] == '.') { // If we're at the end of the thought, then print out the thought.
for (byte k = 0; k < 15; k++) {
for (byte z = newLineStr[k]; z < newLineStr[k + 1]; z++) {
if (z != newLineStr[k] || z == 0) { // If we ARE on character 0 (which is a letter) or we're NOT on the space character (' ') that starts the next line
Serial.print(thoughtStr[z]);
if (z == lastCharNum - 1) { // If we're on the last character of the thought, then print a period.
Serial.println(thoughtStr[z + 1]);
break;
}
} else { // If we ARE on the beginning of the line (which is a space charcter, and not a period), then make a line break to start a new line
Serial.println();
}
}
}
}
}
}
}