Add char at intervals in a String I'm trying to create a function that will take a String as an input, and at every 20 characters, it will instert &quot;\n&quot; so that the string doesn't go off the side of my screen (I'm using an oled with the SSD1306Ascii library).
This is my code so far, but when I run it nothing appears on the screen (I have another part of the code which passes the string to the funtion):
String message = &quot;&quot;;
String newMessage = &quot;&quot;;

void printMessage(String message) {
  oled.clear();
  if(message.length() &gt; 20) {
    current = 20;
    while(current &lt; message.length()) {
      newMessage = message.substring(current-20, current) + &quot;\n&quot;;
      newMessage = newMessage + message.substring(current+1);
      current+20;
    }
    oled.println(newMessage);
  }
  else {
    oled.println(message);
  }
}
One issue with both your failed implementation and the previous answer
is that they do loads of dynamic allocations and copies. Every time you
use the String’s + or += operators you are allocating heap memory
for a brand new String, copying the original character data into the
newly allocated space, and eventually destroying the original Strings
when you don’t need them anymore.
The simplest way to avoid all these copies and allocations is to not
build the String you want. Instead, just write() the pieces one after
the other on the display. Here is a zero-copy, zero-dynamic allocation
solution:
void printMessage(const char *message) {
    size_t length = strlen(message);
    while (length &gt; 20) {
        oled.write(message, 20);
        oled.write('\n');
        message += 20;  // point to the rest of the message
        length  -= 20;  // remaining length
    }
    oled.write(message);
}

Note that the method Print::write(const char *, size_t) is used here
to print a slice of the message without ever building it as a string in
memory.
On these memory-constrained devices it is always preferable to avoid
heap allocation, and thus String objects. However, if for whatever
reason you really need to print a String object, then you can use
the following overload to print it’s internal buffer without making any
extra copy:
void printMessage(const String &amp;message) {
    printMessage(message.c_str());
}