how to delete the last character of a string

Nov 22, 2009 at 9:39am
Hey!
Can someone explain to me how to delete the last character of a string, for example:

string example = "example";

I need it to contain "exampl"

Please help!
Nov 22, 2009 at 10:00am
Do you need it to cout? Because you could make it into an array and cout the array, minus the last character.
Nov 22, 2009 at 10:04am
yes, how do i do that?
Nov 22, 2009 at 10:19am
Nov 22, 2009 at 10:27am
example plz?
Nov 22, 2009 at 11:46am
Nov 23, 2009 at 1:25am
1
2
3
char[] example = "example";
int len = strlen(example);
example[len - 1] = NULL;
Last edited on Nov 23, 2009 at 1:26am
Nov 23, 2009 at 4:24pm
@Kangaroux: You really shouldn't be setting a char to NULL because that is supposed to be used with pointers. Even though it does end up being the same as assigning it to the null character ('\0').
Nov 23, 2009 at 4:29pm
1
2
3
4
string myString = "Hello John Doe";
string newString;

newString = myString.substr(0, myString.length() - 1);
Nov 23, 2009 at 8:21pm
@Zhuge: Using someChar[i] = NULL; is perfectly fine. You only run into some trouble when you do someChar = NULL;
Nov 23, 2009 at 8:25pm
Kangaroux wrote:
@Zhuge: Using someChar[i] = NULL; is perfectly fine. You only run into some trouble when you do someChar = NULL;
Zhuge wrote:
You really shouldn't be setting a char to NULL because that is supposed to be used with pointers.
Nov 23, 2009 at 9:34pm
I'm not going to argue about this, all I said is that setting it to NULL will work, which it does. I could care less if it was "meant" to be used with pointers instead.
Last edited on Nov 23, 2009 at 9:34pm
Nov 23, 2009 at 11:57pm
No, don't set it to NULL, you should instead set it to something like:

someChar[i] = (pow(e,(i*PI))+1);
Nov 24, 2009 at 12:35am
Kangaroux wrote:
I'm not going to argue about this, all I said is that setting it to NULL will work, which it does. I could care less if it was "meant" to be used with pointers instead.


You should. Sure it works (assuming NULL is 0), but anyone else who reads it would very likely be confused into thinking it's an array of pointers or something. And if they did get what you were doing, it would look like you don't understand the difference between the NUL character and a null pointer. Saying that it doesn't matter how it looks if it works is not a good philosophy.
Topic archived. No new replies allowed.