Just Dragos
Just Dragos

Reputation: 19

How do I erase last character of a string without "erase()"?

I am trying to erase the last character of a string without "erase()",

from "ABC" to "AB"

I tried setting the last character to NULL a[strlen(a) - 1] = NULL, but it doesn't solve my problem.

Upvotes: 1

Views: 1089

Answers (2)

smalik
smalik

Reputation: 373

you can also try substr() if you want to preserve original string.

std::string b = a.substr (0,a.length()-1);  

Upvotes: 0

Priyul Mahabeer
Priyul Mahabeer

Reputation: 21

If you're using C++11, then:

a.pop_back();

Alternatively:

if (a.size () > 0)  
a.resize(a.size()-1);

Upvotes: 2

Related Questions