Created
May 5, 2014 09:46
-
-
Save WalterInSH/11532685 to your computer and use it in GitHub Desktop.
format a string
This file contains 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
/** | |
* User: walter | |
* Date: 5/5/14 | |
* Time: 5:09 PM | |
*/ | |
public class StringFormatter { | |
static final String DELIM_STR = "{}"; | |
/** | |
* Format a string. <br/> | |
* | |
* StringFormatter.format("/user/{}/info",123) // "/user/123/info" <br/> | |
* | |
* @param pattern | |
* @param params | |
* @return | |
*/ | |
final public static String format(final String pattern, Object... params) { | |
if (pattern == null) { | |
return ""; | |
} | |
if (params == null) { | |
return pattern; | |
} | |
int i = 0; | |
int j; | |
StringBuffer sbuf = new StringBuffer(pattern.length() + 50); | |
int L; | |
for (L = 0; L < params.length; L++) { | |
j = pattern.indexOf(DELIM_STR, i); | |
if (j == -1) { | |
// no more variables | |
if (i == 0) { // this is a simple string | |
return pattern; | |
} else { // add the tail string which contains no variables and return | |
// the result. | |
sbuf.append(pattern.substring(i, pattern.length())); | |
return sbuf.toString(); | |
} | |
} else { | |
// normal case | |
sbuf.append(pattern.substring(i, j)); | |
appendParameter(sbuf, params[L]); | |
i = j + 2; | |
} | |
} | |
// append the characters following the last {} pair. | |
sbuf.append(pattern.substring(i, pattern.length())); | |
if (L < params.length - 1) { | |
return sbuf.toString(); | |
} else { | |
return sbuf.toString(); | |
} | |
} | |
private static void appendParameter(StringBuffer sb, Object o) { | |
String oAsString = o.toString(); | |
sb.append(oAsString); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment