views:

142

answers:

6

Hi I have big paragraph with some special characters as %1 , %2, %3

I need to know if there is any design pattern to replace those with proper values and create final paragraph. For Example: Following is my static paragraph.

%1 is beautiful country , %2 is the capital of %1, %1 national language is %3.

I get values of %1,%2, %3 by some source.

A: 

It depends on your programming language really. In C# (.net) you could use:

var replaced = string.Format("{0} is a {1}", "klausbyskov", "donkey");
klausbyskov
Language is C++
Avinash
+1  A: 

I'm not sure if there is a design pattern for this, but it looks like you want to incorporate some templating into your application.

Example of templating with jinja 2:

>>> from jinja2 import Template
>>> template = Template('{{ country }} is a beautiful country!')
>>> template.render(country='India')
India is a beautiful country.

Or just search-and-replace ...

The MYYN
answered Q before the title was changed to "C++ ..."; so feel free to downvote ..
The MYYN
Sorry for that, But I wanted to little clear.
Avinash
+1  A: 

What you are describing is building a parser. For something as simple as your problem, you would probably want to keep the design simple and use the search-replace mechanism for strings available in most languages.

If you need something more powerful (for instance, to allow "%1" in the final string), I would look into using a regex or CFG engine, if this is something you plan on using in the real world, as dealing with edge cases (such as %%1%1%%%1%) can get quite complex.

BlueRaja - Danny Pflughoeft
A: 

I did not get your question completely. But I think you can look at how MessageFormat works in Java. Here is an example -

 int fileCount = 1273;
 String diskName = "MyDisk";
 Object[] testArgs = {new Long(fileCount), diskName};

 MessageFormat form = new MessageFormat(
     "The disk \"{1}\" contains {0} file(s).");

 System.out.println(form.format(testArgs));
Shamik
+1  A: 

If this is C++ then you've a couple of choices for string formatting

  1. boost::string algorithms
  2. printf (though this may not work exactly like you want it to.)
  3. std::string::replace (can get messy)
Glen
Or just Boosts String Algorithms: http://www.boost.org/doc/libs/1_41_0/doc/html/string_algo/usage.html#id1701549
Georg Fritzsche
@gf, yes. I really do need to brush up on my boost sometime soon. Haven't used it in years.
Glen
A: 

you can use strstr or sscanf to find string pointers to a semi-pattern(both are part of the c std library), how ever, to replace, you would need to expand the memory block to accommodate the replacements(if they are bigger), have a look at grep(for unix), or see some of the string search algo's, like Boyer-Moore.

You can also have a look at the google template system or pegtl

Necrolis