Skip to content

Instantly share code, notes, and snippets.

@WalterInSH
Created May 5, 2014 09:46
Show Gist options
  • Select an option

  • Save WalterInSH/11532685 to your computer and use it in GitHub Desktop.

Select an option

Save WalterInSH/11532685 to your computer and use it in GitHub Desktop.

Revisions

  1. WalterInSH revised this gist May 5, 2014. 1 changed file with 0 additions and 2 deletions.
    2 changes: 0 additions & 2 deletions StringFormatter.java
    Original file line number Diff line number Diff line change
    @@ -1,5 +1,3 @@
    package com.vipshop.userbench.util;

    /**
    * User: walter
    * Date: 5/5/14
  2. WalterInSH created this gist May 5, 2014.
    69 changes: 69 additions & 0 deletions StringFormatter.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,69 @@
    package com.vipshop.userbench.util;

    /**
    * 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);
    }
    }