Skip to content

Instantly share code, notes, and snippets.

@ClickerMonkey
Last active August 29, 2015 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ClickerMonkey/bb3113425f145ed7d0a6 to your computer and use it in GitHub Desktop.
Save ClickerMonkey/bb3113425f145ed7d0a6 to your computer and use it in GitHub Desktop.
A simple string templating utility.
public class StringTemplate
{
public static final String DEFAULT_START = "{";
public static final String DEFAULT_END = "}";
private String[] chunks;
public StringTemplate( String text )
{
this( text, DEFAULT_START, DEFAULT_END );
}
public StringTemplate( String text, String start, String end )
{
this.chunks = parse( text, start, end );
}
public String generate( Map<String, ? extends Object> map, String nullValue )
{
if (chunks == null)
{
return null;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < chunks.length; i++)
{
if ((i & 1) == 0)
{
sb.append( chunks[i] );
}
else
{
Object value = map.get( chunks[i] );
sb.append( value == null ? nullValue : value.toString() );
}
}
return sb.toString();
}
public static String[] parse( String text, String start, String end )
{
if (text == null || start == null || start.length() == 0 || end == null || end.length() == 0)
{
return null;
}
List<String> chunkList = new ArrayList<String>();
int last = 0;
int current = 0;
int next = 0;
while (current != -1)
{
current = text.indexOf( start, last );
if (current == -1)
{
chunkList.add( text.substring( last ) );
}
else
{
int wordBegin = current + start.length();
next = text.indexOf( end, wordBegin );
if (next == -1)
{
return null;
}
else
{
chunkList.add( text.substring( last, current ) );
chunkList.add( text.substring( wordBegin, next ) );
}
last = next + end.length();
}
}
return chunkList.toArray( new String[chunkList.size()] );
}
public static void main( String[] args )
{
StringTemplate st = new StringTemplate( "Hello, ${a}! ${ff}", "${", "}" );
Map<String, String> map = new HashMap<String, String>();
map.put( "a", "world" );
String result = st.generate( map, "meow" );
System.out.println( result );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment