views:

57

answers:

2

I have a string with this format:

"key=some value|otherkey=other value|key3=yet another value"

I need to create a function with this signature:

public String update(String all,String key, String value)

Where all is the previous string, key the given key to replace (or add) and value the new value.

I thought about some solutions but they are hard to read and not very elegant. I was hoping one of you guys could come with something that looks better.

PS: I have no problem in using regexes but it needs to be done without any 3rd party lib, just the standar java lib.

Thanks!

+1  A: 

Can I ask why you're using a String for this? I realize it is probably too late to change at this stage, but wouldn't a "Map" be better for this kind of processing? Then you could simply just update using the very apt (in this case) Map methods?

Example:

myMap.put(K key, V value)//you could use a HashMap maybe.

SP

Split Personality
Its a cookie. Thanks
Pablo Fernandez
+1  A: 

Simple code below, without regexes.

public String update(String all, String key, String value) {    
    StringBuilder result = new StringBuilder();
    boolean replaced = false;   
    for (String old : all.split("[|]")) {
        if (old.startsWith(key + "=")) {
            replaced = true;
            result.append("|" + key + "=" + value);
        } else {
            result.append("|" + old);
        }
    }
    if ( ! replaced) {
        result.append("|" + key + "=" + value);
    }    
    return result.toString().substring(1); // avoid initial '|'
}
tucuxi
Wow! Nice way of stripping the extra pipe. I used to put the extra one at the end, and then do some weird substring-fu. This way is *so* much better!
Pablo Fernandez
Only works because the string is guaranteed not to be empty. Otherwise, an if-statement would have been unavoidable.
tucuxi