beldaz
beldaz

Reputation: 4471

Supporting case conversion in StringSubstitutor

I'm using StringSubstitutor to complete strings following a user-defined template such as "I program in ${language}".

Map valuesMap = HashMap();
valuesMap.put("language", "Java");
String templateString = "I program in ${language}.";
StrSubstitutor sub = new StrSubstitutor(valuesMap);
String resolvedString = sub.replace(templateString);

to give "I program in Java".

This works great, but sometimes the template needs to include some transformation of the replacement variable, most often to convert its case. What I'd really like to do is allow patterns along the lines of "I program in ${language:upper}" or "I program in ${upper(language)}" so that the result from above would be "I program in JAVA"

So my questions are:

  1. Does StringSubstitutor already support this (and if so, what''s the syntax)?; otherwise
  2. Is there a way to build on top of StringSubstitutor to support this functionality?; or
  3. Are there other libraries available that would do what I'm after?

Upvotes: 1

Views: 4901

Answers (1)

Coder-Man
Coder-Man

Reputation: 2531

This should work:

valuesMap.put("language:lower", "java");
valuesMap.put("language:upper", "JAVA");

You can write a function that makes sure you put both variants into HashMap.

void put(HashMap hashMap, String key, String value) {
    hashMap.put(key + ":lower", value.toLowerCase());
    hashMap.put(key + ":upper", value.toUpperCase());
}

You can also extend HashMap, like so:

class MyHashMap extends HashMap {
    @Override
    public Object put(Object key, Object value) {
        String strKey = (String)key;
        String strValue = (String)value;
        super.put(strKey + ":lower", strValue.toLowerCase());
        super.put(strKey + ":upper", strValue.toUpperCase());
        return strKey;
    }
}

And then use it like so:

public static void main(String[] args) {
    MyHashMap myHashMap = new MyHashMap();
    myHashMap.put("test", "test");
    System.out.println(myHashMap.get("test:lower"));
    System.out.println(myHashMap.get("test:upper"));
}

Upvotes: 2

Related Questions