1

Hello I have an Arduino programme that has a string with the words hello in it. I can add characters and other strings to the end of that one using:

   String test = "hello";
   test+=" jack";

it would then say "hello jack" The problem is I want to get rid of the last character of the string every 2 seconds so it would be "hello jac" then "hello ja" and so on. How can I do this?

3 Answers 3

4

You may use remove() method to remove last character.

String s = "1234567890";
while(s.length() > 0) {
    int lastIndex = s.length() - 1;
    s.remove(lastIndex);
    Serial.println(s);
}
3
  • Could you please include an example to your answer?
    – Avamander
    Feb 29, 2016 at 18:24
  • 1
    @Avamander Example provided. :) Feb 29, 2016 at 21:50
  • Two typos there: Sstring and lenght.
    – Nick Gammon
    Mar 1, 2016 at 1:41
3

I want to get rid of the last character of the string every 2 seconds so it would be "hello jac" then "hello ja" and so on. How can I do this?

This is how you could do that. Avoid using String and putting the string constants in program memory.

// A buffer for the message
const size_t MSG_MAX = 16;
char msg[MSG_MAX];

void setup()
{
  Serial.begin(9600);
  while (!Serial);
}

void loop()
{
  static int len = 0;
  // Check if it is time to create the initial message
  if (len == 0) {
    strcpy_P(msg, (const char*) F("hello"));
    strcat_P(msg, (const char*) F(" jack"));
    len = strlen(msg) - 1;
  }
  // Otherwise shorten the message
  else {
    msg[len--] = 0;
  }
  // And print current message
  Serial.println(msg);
  delay(2000);
}
3

You are best of learning about C-style strings rather than the String class. The String class can eventually fragment dynamic memory.

To shorten a string a simple method is to move the "string terminator" inwards by overwriting the last byte of the message with zero, like this:

const size_t MSG_MAX = 20;
char msg [MSG_MAX];

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();

  strcpy (msg, "hello");  // initial message
  strcat (msg, " jack");  // concatenate more stuff
  }  // end of setup

  void loop ()
    {
    if (strlen (msg) > 0)
      {
      Serial.println (msg);  // display current message
      msg [strlen (msg) - 1] = 0;  // move null-terminator in
      delay (1000);
      }  // end of any message left

    }  // end of loop

Results:

hello jack
hello jac
hello ja
hello j
hello 
hello
hell
hel
he
h

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.