Here you can find the source of substitute(String template, String[] values)
Parameter | Description |
---|---|
template | the template string. |
values | the values of the variables. |
public static String substitute(String template, String[] values)
//package com.java2s; public class Main { /**// www .j av a 2s. c o m * Performs variable substitution on a template string. * * <p>The variables are formed of the dollar sign followed by a digit, ranging * from 1 to 9. Special variable formed of the dollar singn followed by an * asterisk is substitued with the remaining values separated by * commas. Dollar sign followed by another dollar sign expands to single * dollar sign. If there are not enough values provided, undefined variables * will be substitutes with empty strings. Examples: * <table> * <tr><td>template</td><td>values</td><td>result</td></tr> * <tr><td>$1 rules</td><td>{"ziu"}</td><td>ziu rules</td></tr> * <tr><td>$1 said "$2"</td><td>{"Fred","Foo!"}</td><td>Fred said * "Foo!"</td></tr> * <tr><td>"$2" said $1</td><td>{"Fred","Foo!"}</td><td>"Foo!" said * Fred</td></tr> * <tr><td>$1 likes the following colors: * $*</td><td>{"Mike","blue","grey","cyan"}</td> * <td>Mike likes the following colors: blue, grey, cyan</td></tr> * <tr><td>$1 likes the following $2: * $*</td><td>{"Mike","food","pizza","french fries"}</td><td>Mike likes * the following food: pizza, french fries</td></tr> * </table></p> * * @param template the template string. * @param values the values of the variables. * @return the output string. */ public static String substitute(String template, String[] values) { StringBuilder buff = new StringBuilder(); int maxUsed = 0; char[] t = template.toCharArray(); for (int i = 0; i < t.length; i++) { if (t[i] == '$' && i < t.length - 1) { if (t[i + 1] == '$') { buff.append('$'); i++; } else if (t[i + 1] > '0' && t[i + 1] < '9') { int v = t[i + 1] - '0'; if (v - 1 < values.length) { buff.append(values[v - 1]); } if (v > maxUsed) { maxUsed = v; } i++; } else if (t[i + 1] == '*') { if (maxUsed < values.length) { for (int v = maxUsed; v < values.length; v++) { buff.append(values[v]); buff.append(", "); } buff.setLength(buff.length() - 2); } i++; } else { buff.append('$'); } } else { buff.append(t[i]); } } return buff.toString(); } }