{ }codelper
查找字符串替换字符串子串P0101

模板填空

第一行给出模板字符串 T。
第二行给出定义数 n,接下来 n 行每行给出 "名字=值"。
值是该行第一个 "=" 之后的所有字符,可以为空。
同一名字被定义多次时,只使用最后一次定义。
把 T 中的占位符 {名字} 替换为该名字的值,在一行中输出结果字符串。
未定义名字的占位符保持 {名字} 不变。
替换进去的值不再检查。
即使值中含有 {名字}、$ 或 \ 等字符,也原样输出。

输入
T 有 1 到 1000 个字符,不以空格开头或结尾。
T 中的 { 和 } 只用于占位符,占位符为 { + 1 到 10 个小写英文字母 + }。
0 ≤ n ≤ 50。
名字为 1 到 10 个小写英文字母。
值为 0 到 30 个可打印 ASCII 字符(可能含 {、}、=、$、\),不以空格开头或结尾
输出
替换占位符后的 T,一行
样例 1 · stdin
Dear {name}, your code is {code}. {name}, see {link}.
3
name=Jun
code={name}$1
name=Mina
stdout
Dear Mina, your code is {name}$1. Mina, see {link}.
样例 2 · stdin
{first} and {second}
2
first={second}
second=B
stdout
{second} and B
main.py
输入(stdin)

运行时这些行会依次作为 input()/标准输入传入(运行中不会等待输入)。

$ 就绪

请在电脑上打开以编写和运行代码。在手机上可以查看题目和题解。

其他语言怎么写?查看各语言题解 · 8 种语言题解

关键是把模板从左到右只扫描一遍。
按名字依次调用 replace,前面放进去的值里的 {second} 会在后面再被替换(第二个示例)。
从替换的位置重新查找也是同样的错误;值里含有自己的名字时(a=<{a}>)甚至不会结束。
一遍扫描的方法有两种。
一种是给正则 \{([a-z]+)\} 传替换函数:Python re.sub(pat, fn, t),JS·TS t.replace(/…/g, fn),C# Regex.Replace(t, pat, m => …),Java matcher.replaceAll(r -> …)。
另一种是查找 {(find·indexOf·strchr),把它前面的部分截取拼接后继续前进。
C·C++·Craykon 用这种方法。
还有三个陷阱。
JS 像 t.replace("{a}", v) 这样传字符串只替换第一个;要全部替换请用 replaceAll 或 /g 正则。
JS 中替换值不用函数而用字符串传入时,$&·$1·$$ 有特殊含义;Python re.sub 的字符串替换值也会把 \1 读作分组。
Java 即使给 replaceAll 传函数,也会解读返回字符串里的 $1·\,所以要用 Matcher.quoteReplacement 包起来。
C# MatchEvaluator 返回的值原样插入。
Craykon 用 rest.查找位置("{") 查找,用 rest.截取(0, open) 截取。
查找位置 不能指定起始位置,所以在切掉已处理前段的 rest 中再次查找。

Pythonmain.py · 17 行
import re template = input()n = int(input())values = {}for _ in range(n):    key, value = input().split("=", 1)    values[key] = value  # 같은 이름이 또 나오면 나중 값이 이긴다  def fill(m):    # 정의된 이름이면 값을, 아니면 {이름} 그대로    return values.get(m.group(1), m.group(0))  # 바꾸기 함수를 넘기면 값 안의 {..}나 \1을 다시 읽지 않는다print(re.sub(r"\{([a-z]+)\}", fill, template))
JavaScriptmain.js · 11 行
const lines = require("fs").readFileSync(0, "utf8").split("\n");const template = lines[0];const n = Number(lines[1]);const values = new Map();for (let i = 2; i < 2 + n; i++) {  const eq = lines[i].indexOf("=");  values.set(lines[i].slice(0, eq), lines[i].slice(eq + 1));}// 함수를 넘기면 돌려준 문자열을 그대로 넣는다($&·$1을 읽지 않음)const out = template.replace(/\{([a-z]+)\}/g, (whole, key) => (values.has(key) ? values.get(key) : whole));console.log(out);
TypeScriptmain.ts · 12 行
import { readFileSync } from "node:fs";const lines: string[] = readFileSync(0, "utf8").split("\n");const template: string = lines[0];const n: number = Number(lines[1]);const values = new Map<string, string>();for (let i = 2; i < 2 + n; i++) {  const eq: number = lines[i].indexOf("=");  values.set(lines[i].slice(0, eq), lines[i].slice(eq + 1));}// 함수를 넘기면 돌려준 문자열을 그대로 넣는다($&·$1을 읽지 않음)const out: string = template.replace(/\{([a-z]+)\}/g, (whole: string, key: string): string => values.get(key) ?? whole);console.log(out);
JavaMain.java · 25 行
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.HashMap;import java.util.Map;import java.util.regex.Matcher;import java.util.regex.Pattern; public class Main {    public static void main(String[] args) throws IOException {        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));        String template = in.readLine();        int n = Integer.parseInt(in.readLine().trim());        Map<String, String> values = new HashMap<>();        for (int i = 0; i < n; i++) {            String line = in.readLine();            int eq = line.indexOf('=');            values.put(line.substring(0, eq), line.substring(eq + 1));        }        Matcher m = Pattern.compile("\\{([a-z]+)\\}").matcher(template);        // 돌려준 문자열 안의 $와 \는 그룹 참조로 읽히니 quoteReplacement로 감싼다        String out = m.replaceAll(r -> Matcher.quoteReplacement(values.getOrDefault(r.group(1), r.group())));        System.out.println(out);    }}
C#Main.cs · 23 行
using System;using System.Collections.Generic;using System.Text.RegularExpressions; class Program{    static void Main()    {        string template = Console.ReadLine();        int n = int.Parse(Console.ReadLine());        var values = new Dictionary<string, string>();        for (int i = 0; i < n; i++)        {            string line = Console.ReadLine();            int eq = line.IndexOf('=');            values[line.Substring(0, eq)] = line.Substring(eq + 1);        }        // MatchEvaluator가 돌려준 문자열은 그대로 들어간다($ 해석 없음)        string output = Regex.Replace(template, @"\{([a-z]+)\}",            m => values.TryGetValue(m.Groups[1].Value, out string v) ? v : m.Value);        Console.WriteLine(output);    }}
C++main.cpp · 27 行
#include <iostream>#include <string>#include <unordered_map> int main() {    std::string t, line;    std::getline(std::cin, t);    std::getline(std::cin, line);    int n = std::stoi(line);    std::unordered_map<std::string, std::string> values;    for (int i = 0; i < n; i++) {        std::getline(std::cin, line);        auto eq = line.find('=');        values[line.substr(0, eq)] = line.substr(eq + 1);    }    std::string out;    std::size_t pos = 0;    for (auto open = t.find('{'); open != std::string::npos; open = t.find('{', pos)) {        auto close = t.find('}', open);        out += t.substr(pos, open - pos);        auto it = values.find(t.substr(open + 1, close - open - 1));        out += it != values.end() ? it->second : t.substr(open, close - open + 1);        pos = close + 1; // 넣은 값은 다시 보지 않고, 템플릿의 그다음부터 찾는다    }    out += t.substr(pos);    std::cout << out << '\n';}
Cmain.c · 46 行
#include <stdio.h>#include <string.h> static char keys[50][11], vals[50][32];static int count = 0; /* 이름이 정의돼 있으면 그 값, 없으면 NULL. 나중에 넣은 것이 이기도록 뒤에서부터 찾는다 */static const char *lookup(const char *key) {    for (int i = count - 1; i >= 0; i--)        if (strcmp(keys[i], key) == 0) return vals[i];    return NULL;} int main(void) {    static char t[1100], line[64];    int n;    fgets(t, sizeof t, stdin);    t[strcspn(t, "\n")] = '\0';    fgets(line, sizeof line, stdin);    sscanf(line, "%d", &n);    for (int i = 0; i < n; i++) {        fgets(line, sizeof line, stdin);        line[strcspn(line, "\n")] = '\0';        char *eq = strchr(line, '=');        *eq = '\0';        strcpy(keys[count], line);        strcpy(vals[count], eq + 1);        count++;    }    const char *p = t;    const char *open;    while ((open = strchr(p, '{')) != NULL) {        const char *close = strchr(open, '}');        fwrite(p, 1, open - p, stdout);            /* { 앞까지 그대로 */        char key[16];        int len = (int)(close - open - 1);        memcpy(key, open + 1, len);        key[len] = '\0';        const char *v = lookup(key);        if (v) fputs(v, stdout);        else fwrite(open, 1, close - open + 1, stdout); /* 없는 이름은 {이름} 그대로 */        p = close + 1;    }    puts(p);    return 0;}
Craykonmain.cray · 31 行
t = 控制台.读行();n = 控制台.读行().转数字();values = 字典();循环 (i = 0; i < n; i++){    line = 控制台.读行();    eq = line.查找位置("=");    values[line.截取(0, eq)] = line.截取(eq + 1);}out = "";rest = t;open = rest.查找位置("{");当 (open != -1){    close = rest.查找位置("}");    key = rest.截取(open + 1, close - open - 1);    out += rest.截取(0, open);    如果 (values.包含(key))    {        out += values[key];    }    否则    {        out += rest.截取(open, close - open + 1);    }    // 넣은 값은 다시 보지 않고, 템플릿의 남은 부분에서만 찾는다    rest = rest.截取(close + 1);    open = rest.查找位置("{");}out += rest;控制台.输出(out);