CodersSC
CodersSC

Reputation: 710

C++ Strings adding at the start and at the end

I want to add a ^ at the start of the string and a $ at the end.

std::string s1 (".V/.B/.R/");

Is the best way to use ?

s1.append(s1.begin(),"^");
s1.append(s1.end(),"$");

Thanks for any help.

Upvotes: 1

Views: 1588

Answers (3)

Bo Persson
Bo Persson

Reputation: 92211

It would be insert rather than append, but otherwise it seems ok.

An even easier way would be

s1 = '^' + s1 + '$';

Upvotes: 7

Konrad
Konrad

Reputation: 40947

Your examples won't work as they don't use any of the stl::string::append overloads, you can create a new string and add the elements individually, i.e.

std::string FormatText( const std::string& rstrInput )
{
    std::string strOutput = "^"; 
    strOutput += rstrInput ;
    strOutput += "$";
    return strOutput;    // RVO will eliminate copying
}

But there are probably a number of ways of doing this, appending is probably the simplest.

std::string strResult = "^" + strValue + "$";

You could also use stringstreams..

std::stringstream ss;
ss << "^" << strValue  << "$";
std::string strResult = ss.str();

... printf style string formation etc etc..

Upvotes: 2

hmjd
hmjd

Reputation: 121961

You cannot use std::string::append() in that way:

s1.insert(0, "^");
s1.append("$");

Upvotes: 2

Related Questions