Template Replace

Template Replace

Hard PHP PHP Variables 22 views
Explanation Complexity

Problem Statement

You get n pairs key value, then one text line. Replace {key} with value and print final text.

Input Format

Line1 n. Next n lines: key value. Last line: text.

Output Format

One line text.

Example

2
name Ravi
city Pune
Hello {name} from {city}!
Hello Ravi from Pune!

Constraints

Total length

Input / Output Format

Input Format
Line1 n. Next n lines: key value. Last line: text.
Output Format
One line text.
Constraints
Total length

Examples

Input:
2 name Ravi city Pune Hello {name} from {city}!
Output:
Hello Ravi from Pune!

Example Solution (Public)

PHP
<?php
$inputText=stream_get_contents(STDIN);
$inputLines=preg_split('/\\R/', rtrim($inputText));
if(!$inputLines || trim($inputLines[0])==='') exit;
$n=intval(trim($inputLines[0]));
$mp=[];
$idx=1;
for($i=0;$i<$n;$i++){
  $tokens=preg_split('/\\s+/', trim($inputLines[$idx++] ?? ''), 2);
  $k=$tokens[0] ?? '';
  $v=$tokens[1] ?? '';
  if($k!=='') $mp[$k]=$v;
}
$text=$inputLines[$idx] ?? '';
foreach($mp as $k=>$v) $text=str_replace('{'.$k.'}', $v, $text);
echo $text;
?>

Official Solution Code

<?php
$inputText=stream_get_contents(STDIN);
$inputLines=preg_split('/\\R/', rtrim($inputText));
if(!$inputLines || trim($inputLines[0])==='') exit;
$n=intval(trim($inputLines[0]));
$mp=[];
$idx=1;
for($i=0;$i<$n;$i++){
  $tokens=preg_split('/\\s+/', trim($inputLines[$idx++] ?? ''), 2);
  $k=$tokens[0] ?? '';
  $v=$tokens[1] ?? '';
  if($k!=='') $mp[$k]=$v;
}
$text=$inputLines[$idx] ?? '';
foreach($mp as $k=>$v) $text=str_replace('{'.$k.'}', $v, $text);
echo $text;
?>
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.