My own sprintf(...)

S

Simon

Hi,

I have default const strings that we use as templates to send emails, (and
multi language messages).
We also want to allow the users to format their own messages.

We have specific messages like devices name and certain settings.

I can use sprintf(...) to replace numbers or strings, but how can I replace
my own variables?

for example

const char * szMsg = "#device# was turned on at #time#";

std::string MyFormat( const char * s )
{
std::string szRet = "";
// replace all the #device# with "device number x"
// replace #time# with "12:02:36pm"
// ...and so on...

return szRet;
}

Does the standard have a way of doing search and replace?

Many thanks

Simon
 
I

Ivan Vecerina

Simon said:
for example

const char * szMsg = "#device# was turned on at #time#";

std::string MyFormat( const char * s )
{
std::string szRet = "";
// replace all the #device# with "device number x"
// replace #time# with "12:02:36pm"
// ...and so on...

return szRet;
}

First of all, you may want to take a look at the
boost::format library - it might suit your needs
(although with a different syntax/approach):
http://www.boost.org/libs/format/doc/format.html

Does the standard have a way of doing search and replace?

Almost - it does help to use some wrapper functions.
My personal toolbox includes:

bool replaceFirst(std::string& ioStr, std::string const& findStr,
std::string const& replStr)
{
std::string::size_type const pos = ioStr.find(findStr);
if( std::string::npos == pos )
return false;

ioStr.replace( pos, findStr.size(), replStr );
return true;
}

int replaceAll(std::string& ioStr, std::string const& findStr, std::string
const& replStr)
{
int hits = 0;
for( std::string::size_type pos = 0
; std::string::npos != ( pos = ioStr.find( findStr, pos ) )
; pos += findStr.size()
)
{
ioStr.replace( pos, findStr.size(), replStr );
++hits;
}
return hits;
}


I hope this helps,
Ivan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,152
Latest member
LorettaGur
Top