Best way to wrap a long string for output

I’m sending strings over serial to a thermal printer... could anyone tell me the best way approach for wrapping these strings in arduino?

My instinct is to insert a serial newline (\n) character at the appropriate places in the string.

For reference, this is from an earlier Ruby implementation that was sending strings to the arduino:

def wrap(String s, int cols){
  s.gsub(/(.{1,#{cols}})(\s+|\Z)/, "\\1\n");
}
end

(Sorry for the ugly code) I was basically using a substitution (gsub) to insert a newline (\n) after the last space before the end of the row.

Is there a similar search and replace routine in arduino, or is there an easier way to wrap strings?

Any help appreciated... thanks very much!

My instinct is to insert a serial newline (\n) character at the appropriate places in the string.

If wrap means word-wrap, then that sounds reasonable.

Is there a similar search and replace routine in arduino, or is there an easier way to wrap strings?

That depends on whether you are talking about strings (NULL terminated array of chars) or Strings (instances of the String class), and what you mean by "the end of the row".

I saw nothing in your post that defined either of these items.

Thanks for your reply, sorry if it was unclear.

Yes, I’m trying to do a word wrap on the strings.

At the moment I think I’m using a string (null-terminated array of chars ) – I’m using:

printer.println(“Message here...”);

When I say “the end of the row” I meant the end of the line, the length of which is defined by the variable cols in the ruby code.

When I say “the end of the row” I meant the end of the line, the length of which is defined by the variable cols in the ruby code.

You won't be able to do this directly:

printer.println(“Message here...”);

You could create a function:

void printWrapped(char *msg, int cols)
{
}

and call it:

printWrapped(“Message here...”, 30);

In the function, get the length of the string. If it is less than 30, nothing needs to be done to the string before calling printer.print().

If it is more than 30, use a for loop, starting at 29 counting down. If you find a space, record the position, then print the part of the line up to that position, by changing the space to a NULL.

If there are no spaces, you'll need to copy the character in position 29, replace it with a NULL, and print the string.

Then, replace the NULL with the original character, shuffle the array to the left by the number of characters printed, and repeat the process (using a while loop).

OK, thanks, will give it a try.