import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.TreeSet;
class Main {
public static void main
(String[] args
) { String templateTexto
= "{tag} {player} {abacaxi} {banana} > {msg}"; Map
<String, String
> substituicoes
= new HashMap
<>(); substituicoes.put("tag", "MODERADOR");
substituicoes.put("player", "João");
substituicoes.put("msg", "uma mensagem.");
Template template = new Template(templateTexto);
String substituido
= template.
substituir(substituicoes
); System.
out.
println(substituido
); }
}
class Template {
private final String template
; private final Set<String> tags;
public Template
(String template
) { this.template = template;
this.tags = new TreeSet<>();
StringBuilder nomeVariavel = null;
boolean variavel = false;
for (char c : template.toCharArray()) {
if (!variavel && c == '{') {
variavel = true;
nomeVariavel = new StringBuilder();
} else if (variavel && c == '}') {
variavel = false;
tags.add(nomeVariavel.toString());
nomeVariavel = null;
} else if (variavel) {
nomeVariavel.append(c);
}
}
}
public String substituir
(Map
<String, String
> substituicoes
) { for (Map.
Entry<String, String
> entry
: substituicoes.
entrySet()) { texto = texto.replace("{" + entry.getKey() + "}", entry.getValue());
}
if (substituicoes.containsKey(tag)) continue;
texto = texto.replace("{" + tag + "} ", "");
texto = texto.replace("{" + tag + "}", "");
}
return texto;
}
}
aW1wb3J0IGphdmEudXRpbC5NYXA7CmltcG9ydCBqYXZhLnV0aWwuSGFzaE1hcDsKaW1wb3J0IGphdmEudXRpbC5TZXQ7CmltcG9ydCBqYXZhLnV0aWwuVHJlZVNldDsKCmNsYXNzIE1haW4gewogICAgcHVibGljIHN0YXRpYyB2b2lkIG1haW4oU3RyaW5nW10gYXJncykgewogICAgCVN0cmluZyB0ZW1wbGF0ZVRleHRvID0gInt0YWd9IHtwbGF5ZXJ9IHthYmFjYXhpfSB7YmFuYW5hfSA+IHttc2d9IjsKICAgIAlNYXA8U3RyaW5nLCBTdHJpbmc+IHN1YnN0aXR1aWNvZXMgPSBuZXcgSGFzaE1hcDw+KCk7CiAgICAJc3Vic3RpdHVpY29lcy5wdXQoInRhZyIsICJNT0RFUkFET1IiKTsKICAgIAl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