Let's say I have std::string temp as:

std::string temp = "{abc,def}";

I want the temp to contain "abc,def", i.e. remove the '{' and '}' from beginning and end of the temp.

So I wrote:

temp = temp.substr( 1, temp.length() - 1 );

However after executing it, the temp contains "abc,def}".

What am I missing? Is there an easier way to do what I'd like?

jonrsharpe's user avatar

jonrsharpe

124k31 gold badges281 silver badges491 bronze badges

Igor's user avatar

3

temp = temp.substr( 1, temp.length() - 1 ); - as mentioned in the comments, it gets substring on 1 char shorter, but you want to remove 2 characters, so the proper code: temp = temp.substr( 1, temp.length() - 2 );.

This constructs a new string and is not optimal for long strings. A better inplace solution:

temp.erase(0, 1); // or temp.erase(temp.begin()) temp.pop_back();

3CEZVQ's user avatar

1 Comment

Thx. Your solution works fine. Accepted.

2026-03-02T02:24:34.81Z+00:00

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.