how to delete the last character of a string

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!
Do you need it to cout? Because you could make it into an array and cout the array, minus the last character.
yes, how do i do that?
example plz?
1
2
3
char[] example = "example";
int len = strlen(example);
example[len - 1] = NULL;
Last edited on
@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').
1
2
3
4
string myString = "Hello John Doe";
string newString;

newString = myString.substr(0, myString.length() - 1);
@Zhuge: Using someChar[i] = NULL; is perfectly fine. You only run into some trouble when you do someChar = NULL;
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.
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
No, don't set it to NULL, you should instead set it to something like:

someChar[i] = (pow(e,(i*PI))+1);
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.