Created
March 30, 2024 06:24
-
-
Save YuanLiou/876772dac9eb4ab491347cac5ded0b92 to your computer and use it in GitHub Desktop.
TemplateStringReplacer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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