Reputation: 13257
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.
Upvotes: 0
Views: 647
Reputation: 22300
If this is C++ then you've a couple of choices for string formatting
Upvotes: 1
Reputation: 26171
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
Upvotes: 0
Reputation: 7108
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));
Upvotes: 0
Reputation: 86086
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.
Upvotes: 1
Reputation: 188114
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 ...
Upvotes: 1
Reputation: 120997
It depends on your programming language really. In C# (.net) you could use:
var replaced = string.Format("{0} is a {1}", "klausbyskov", "donkey");
Upvotes: 0