Mad Libs: Difference between revisions

Rewritten D entry, fits better the Task
(Simpler regex in D entry)
(Rewritten D entry, fits better the Task)
Line 212:
 
=={{header|D}}==
{{trans|PythonRuby}}
<lang d>import std.stdio, std.regex, std.arrayalgorithm, std.algorithmstring, std.array;
std.string, std.range;
 
void main() {
writeln("TheEnter a story template, isterminated by an empty line:\n", story);
auto story = "<name> went for a walk in the park. <he or she>
std.string, std.rangestory;
found a <noun>. <name> decided to take it home.";
while (true) {
writeln("The story template is:\n", story);
const values auto line = std.string.split(stdin.readln().strip(), ",");
writeln("\nInput a comma-separated list of words "
if (line.empty) break;
"to replace the following items:");
story ~= story.replace(f,line v)~ "\n";
}
 
auto re = regex("<.+?>", "g");
auto fields = story.match(re).map!q{a.hit}().array().sort().uniq();
writefforeach (" %s: ",field; fields.join(",")); {
writef("Enter a value for '%s': ", field[1 .. $ - 1]);
const values = std.string.split(stdin.readln().strip(), ",");
story = story.replace(field, stdin.readln().strip());
foreach (f, v; zip(fields, values))
}
story = story.replace(f, v);
 
writeln("\nThe story becomes:\n", story);
}</lang>
{{out}}
<pre>TheEnter a story template, terminated by an empty isline:
<name> went for a walk in the park. <he or she>
found a <noun>. <name> decided to take it home.
 
Enter a value for 'he or she': She
Input a comma-separated list of words to replace the following items:
Enter a <hevalue orfor she>,<'name>,<noun>': She,Monica,cockerel
Enter a value for 'noun': cockerel
 
The story becomes: