开发者

Text manipulation in Java

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!


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


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 '|'
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜