Public Group

# Need help with string function

This topic is 4723 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Im coding a little game here. Ive got this string for a merchant that he is supposed to say. Ive made it like this so every merchant can use the same string; "Hi, I can sell you a %o for the price of %p silvercoins, interested?" Where %o is replaced with the object in question and %p is replaced with the price. Ive searched around the msdn but I can seem to find a function that could help med do this. A function that search for the two letter combination %o or %p and replaces them with the right stuff when the function finds it. I did also try to make it into a regular array (which could be easier to manipulate char by char) but it didnt quite work out. Any ideas? Or is there a better way? My ways isnt usually the best :P

##### Share on other sites
If you are replacing text with text, you could use std::basic_string's replace/find methods you can check'em out here plus you have generic algorithms to choose from find a reference here.

if you are going to replace the text with different types of objects (including user-defined types which have an overload stream insertion/extraction operators) when using std::basic_string its best to use string streams.

##### Share on other sites
What's wrong with the good ol' sprintf? :)

btw, the syntax is:
char str[256];sprintf(str,"Hi, I can sell you a %s for the price of %i silvercoins, interested?",object_name,price);

##### Share on other sites
Quote:
 Original post by RaduprvWhat's wrong with the good ol' sprintf? :)

Buffer overflow.

##### Share on other sites
Quote:
 Buffer overflow.

If you don't check the arguments length, sure. But if you are a careful programmer, that shouldn't happen.

##### Share on other sites
O_o but std::string can do that for you.

##### Share on other sites
Quote:
 Original post by RaduprvWhat's wrong with the good ol' sprintf? :)

Lack of straightforward unicode support.

##### Share on other sites
In addition to what's been mentioned already you can use FormatMessage (Windows only) or boost::format. Both of these support numbered arguments which makes localization slightly easier.

##### Share on other sites
Quote:
 Original post by TelastynLack of straightforward unicode support.

The OP didn't need Unicode.
If you need Unicode, just use a library meant for it. If not, just use whatever works for you.

• 33
• 15
• 23
• 10
• 19