R. S.
R. S.

Reputation: 400

Replace a variable in a String

I am looking for a String Utils so that I can do something like this.

String input = "this is the $var on $date"
someUtil.evaluate(input, [var: "end", date: "11/11/11"])

output : this is the end on 11/11/11.

someUtil.evaluate(input, [var: "start", date: "10/10/10"])

output : this is the start on 10/10/10.

Upvotes: 2

Views: 140

Answers (2)

xxxvodnikxxx
xxxvodnikxxx

Reputation: 1277

Do you really need as incoming parameter that "array" ? If not, that you can implement as easy as it is ..

private static String replaceVarByVal(String toReplace,String var,String val){
        return toReplace.replace(var, val);
}

(You can easy modify that to incom params arrays, but better should be eg. Map- key variable, value new value of the "placeholder" - $var)

Arrays variant:

private static String replaceVarByVal(String toReplace,String[] var,String[] val){
        String toRet = toReplace;
        //arrays logic problem 
        if(var.length != val.length){
            return null;
        }else{
            for (int i = 0; i < var.length; i++) {
                toRet = toRet.replace(var[i], val[i]);
            }
        }
        return toRet;
}

Better variant with map:

private static String replaceVarByVal(String toReplace,Map<String, String> paramValsMap){
        String toRet = toReplace;
        for (Map.Entry<String, String> entry : paramValsMap.entrySet())
        {
            toRet=toRet.replace(entry.getKey(), entry.getValue());
        }
        return toRet;
}

(And that can be used universally for anything)

Upvotes: 0

Ralph
Ralph

Reputation: 120861

Use standard java MessageFormat, it is quite powerfull (read its class level JavaDoc)

Date endDate = new GregorialCalendar(2011, Calendar.NOVEMBER, 11).getTime();
...
MessageFormat.format(
      "this is the {0} on {1,date,yy/MM/dd}",
      new Object[]{"end", endDate});

Upvotes: 5

Related Questions