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?

Nick Gammon
38.9k13 gold badges69 silver badges125 bronze badges
asked Jan 31, 2016 at 15:20

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);
}
answered Jan 31, 2016 at 15:26
3
  • Could you please include an example to your answer? Commented Feb 29, 2016 at 18:24
  • 1
    @Avamander Example provided. :) Commented Feb 29, 2016 at 21:50
  • Two typos there: Sstring and lenght. Commented 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);
}
answered Jan 31, 2016 at 15:59
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
answered Jan 31, 2016 at 21:09

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.