StringUtils { public static String replace(String s, Map<String, Object> map) { StringBuilder ret = new StringBuilder((int) (s.length() * 1.5)); int cursor = 0; for (int start, end; (start = s.indexOf("${", cursor)) != -1 && (end = s.indexOf("}", start)) != -1; ) { ret.append(s, cursor, start).append(map.get(s.substring(start + 2, end))); cursor = end + 1; } ret.append(s, cursor, s.length()); return ret.toString(); }  static String[] split(String str); static String[] split(String str, String separatorChars); static String[] split(String str, char separatorChar); static String[] split(String str, String separatorChars, int max); static String[] splitByWholeSeparator(String str, String separator); static String[] splitByWholeSeparator(String str, String separator, int max); static boolean hasText(String str); static boolean hasText(CharSequence str); static boolean hasLength(CharSequence str); static boolean hasLength(String str); static String replace(String s, Map<String, Object> map); static String replace(String s, Object... objs); static String replaceStr(String s, String sub, String with); static String escapeXML(String str); static String unicodeToString(String s); static String getFilenameExtension(String path); static String getFilename(String path); static byte[] getUtf8Bytes(String string); static byte[] getBytes(String string); static int toInt(String string, int from); static void append(StringBuilder buf, byte b, int base); static void append2digits(StringBuilder buf, int i); static String asciiToLowerCase(String s); static String normalizeCharset(String s); static String normalizeCharset(String s, int offset, int length); static boolean isHex(String str, int offset, int length); static String truncate(String str, int maxSize); static final String EMPTY; static final String[] EMPTY_STRING_ARRAY; }
@Test void testReplace() { String str = "hello ${t1} and ${t2} s"; Map<String, Object> map = new HashMap<>(); map.put("t1", "foo"); map.put("t2", "bar"); String ret = StringUtils.replace(str, map); assertEquals(ret, "hello foo and bar s"); map = new HashMap<>(); map.put("t1", "foo"); map.put("t2", "${dddd}"); ret = StringUtils.replace(str, map); assertEquals(ret, "hello foo and ${dddd} s"); map = new HashMap<>(); map.put("t1", null); map.put("t2", "${dddd}"); ret = StringUtils.replace(str, map); assertEquals(ret, "hello null and ${dddd} s"); map = new HashMap<>(); map.put("t1", 33); map.put("t2", 42L); ret = StringUtils.replace(str, map); assertEquals(ret, "hello 33 and 42 s"); }
@Test void testReplace2() { String str2 = "hello {{{{} and {} mm"; String ret2 = StringUtils.replace(str2, "foo", "bar"); assertEquals(ret2, "hello {{{foo and bar mm"); ret2 = StringUtils.replace(str2, "foo"); assertEquals(ret2, "hello {{{foo and {} mm"); ret2 = StringUtils.replace(str2, "foo", "bar", "foo2"); assertEquals(ret2, "hello {{{foo and bar mm"); ret2 = StringUtils.replace(str2, 12, 23L, 33); assertEquals(ret2, "hello {{{12 and 23 mm"); }