Skip to content

Instantly share code, notes, and snippets.

@YuanLiou
Created March 30, 2024 06:24
Show Gist options
  • Save YuanLiou/876772dac9eb4ab491347cac5ded0b92 to your computer and use it in GitHub Desktop.
Save YuanLiou/876772dac9eb4ab491347cac5ded0b92 to your computer and use it in GitHub Desktop.
TemplateStringReplacer
import java.util.Map;
public class TemplateStringReplacer {
public static String createStringFromTemplate(Map<String, Integer> map, String template) {
StringBuilder stringBuilder = new StringBuilder();
String[] elements = template.split("%");
for (String element : elements) {
if (element.equals("_")) {
stringBuilder.append("_");
} else if (map.containsKey(element)) {
stringBuilder.append(map.get(element));
} else {
// If the element in the template is not found in the map,
// TODO: you might want to discuss with the interviewer how to handle it.
// For now, we do nothing.
}
}
return stringBuilder.toString();
}
public static void main(String[] args) {
// Using Java 9's of() method for simplicity.
Map<String, Integer> map = Map.of("X", 123, "Y", 456);
String template = "%X%_%Y%";
System.out.println(createStringFromTemplate(map, template));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment