从分隔字符串中提取

时间:2017-05-25 14:22:27

标签: java

希望评论这是否是解析特定键的竖线分隔字符串的最佳/推荐方法。
在针对每个请求运行此操作的低延迟系统中 - 低效率是昂贵的。

 public String extractFields(String key,String comment){
        if(comment!=null){
            for(String test:comment.split("\\|")){
                if(test.contains(key)){
                    return test.substring(test.indexOf(key)+key.length()).trim();
                }
            }
        }
        return null;
    }

2 个答案:

答案 0 :(得分:0)

嗯,分裂和搜索似乎对我来说毫无意义。

为什么不:

  • indexOf()获取其位置的密钥,测试这是否有效
  • 如果有效,请从该位置indexOf()到下一个|
  • 返回上述区域的子字符串。

答案 1 :(得分:0)

根据Nim的回答,这是实现更快捷方式的实现:

public String extractField(String key, String comment) {
    if (key == null || comment == null)
        return null;
    int i = comment.indexOf(key);
    if (i < 0) // Does not contain the key
        return null;
    String result = comment.substring(i + 1);
    i = result.indexOf('|');
    if (i >= 0)
        result = result.substring(0, i);
    return result;
}
相关问题