2

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.

4
  • 1
    havent used spring classes for any string manipulation. Surprisingly there is class for StringUtils (docs.spring.io/spring-framework/docs/3.2.0.M1/api/org/…). But Even they suggest use of apache common api Commented Dec 2, 2015 at 6:54
  • 1
    You could probably implement on your own using Map and String.replaceFirst(regex, replacement) Commented Dec 2, 2015 at 6:54
  • Why do you need to use a Spring utility? Can't you use SimpleDateFormat? System.out.println(new SimpleDateFormat("yy/MM/dd").format(new Date())); Commented Dec 2, 2015 at 6:59
  • @saurabh Thanks apache common StrSubstitutor solves the problem Commented Dec 2, 2015 at 7:03

2 Answers 2

5

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});
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.