1

Assume there is a string:

"I'm a boy."

and some synonyms words (in key-value format):

boy -> "male yong"
yong -> "age under 18"

If I replace the string by synonyms words one by one, it will be:

Step 1, find word "boy" and replace it: "I'm a male young." Step 2, find word "young" and replace it: "I'm a male age under 18." Actually I need not recursive replacement, I need only replace the orginal string, in other words the step 2 should find "young" in orginal string:"I'm a boy." not the "I'm a male young." There is a simple solution:

Firstly replace key to %s and add synonyms word to a list:

string: "I'm a %s"
list: "male yong"

Then format string with list:

String.format(string, list)

It works fine but stupid and slow, anyone have more clear solution?

4

2 回答 2

1

伪代码(未经测试,函数名称可能有误):

String[] arr = sentence.Split(" ");
StringBuilder sb = new StringBuilder(); //can specify size for better results possibly

for (String s :arr ){
   if ( dic.contains(s) ){
       sb.append(dic.get(s));
   }else{
       sb.append(s);
   }
}

sb.toString();//your replaced string

我不确定 string.format 在内部做了什么,但它可能会做类似的事情,所以我怀疑你会得到性能提升。

于 2013-05-06T02:06:01.757 回答
0

此解决方案与您的类似,但不使用 String.format

    String s = "I'm a yong boy.";
    Map<String, String> map = new HashMap<>();
    map.put("boy", "male yong");
    map.put("yong", "age under 18");
    // replace all keys with 1 char placeholders 
    int i = 0;
    for (String key : map.keySet()) {
        s = s.replace(key, "" + (char) i++);
    }
    // replace placeholders with values
    int j = 0;
    for (String v : map.values()) {
        s = s.replace("" + (char) j++, v);
    }
    System.out.println(s);

输出

I'm a age under 18 male yong.

如果我们使用 StringBuilder 进行替换,可以提高速度,但代码会更长。替换号小于31是安全的,之后会开始替换空格

于 2013-05-06T03:07:35.750 回答