Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
10 years, 9 months ago.
Delete last character in a string
Silly question, but is there a simple way to remove the last character in a string and resize length accordingly?
Code
char ssid[26]; ssid.resize (ssid.size () - 1); // Error: Expression must have class type in "main.cpp"
1 Answer
10 years, 9 months ago.
Hi Paul,
Being more a c-programmer than c++, and starting with this:
char ssid[26]; // allocate 26 bytes to ssid, whether we use it or not.
Here's my thinking for what you are asking:
char * ssid = (char *)malloc(26); // allocate 26 bytes (for now) strcpy(ssid, "123456"); // ssid now has "123456\0" ssid = (char *)realloc(ssid, 25); // realloc preserves what it can, but caution: it will not move the NULL terminator ssid = (char *)realloc(ssid, 3); // preserves to "123", but we have no idea what comes after 3, a 4, a NULL, or garbage. int ssidlen = strlen(ssid); // so I won't predict the answer to this, and it might not be consistent depending on the memory manager.
Your title says to delete last character, so let me explore another possibility:
char ssid[26] = "123456"; // only occupying 7 of the 26 (7 counts the NULL terminator "123456\0") int ssidlen = strlen(ssid); // ssidlen has 6, since it stops at the NULL. ssid[strlen(ssid) - 1] = '\0'; // find the last character position (the '6'), backup 1 and stuff NULL in there ssidlen = strlen(ssid); // newlen now has 5
This latter version does not reduce the 26 byte allocation, but all uses of ssid now have a shorter string. For this scenario I assumed ssid contains text, and therefore the NULL termination was needed.
And unrelated to your question - but if "ssid" refers to Wi-Fi ssid, the common references say it could be a maximum of 32 characters in length (and some indications that some systems only permit 31), so 26 might be a little shy of a fully flexible solution.
Thank you David, making a bit more sense now.
Nice if I could use pop_back
http://www.cplusplus.com/reference/vector/vector/pop_back/
I'm using a touch screen soft keyboard and the idea is if I mistype character's I need to delete or 'backspace' like you would on a PC keyboard. I would need to end up with the correct byte amount to pass to the Wi-Fi module. And yes I will need to extend the allocation to a maximum of 32 (when I get this bit working, I'll need to reduce font size to get it in one line, but that's no problem).
I'll give this a try and see what happens.
Edit...
Works fine David, many thanks. (can't accept answer for some reason)
Paul
posted by 22 Jan 2015