我有以下字符串,可能包含约100个条目:
String foo = "{k1=v1,k2=v2,...}"
Run Code Online (Sandbox Code Playgroud)
我正在寻找以下功能:
String getValue(String key){
// return the value associated with this key
}
Run Code Online (Sandbox Code Playgroud)
我想在不使用任何解析库的情况下执行此操作.什么想法快速的东西?
Jam*_*nen 12
如果您知道您的字符串将始终如下所示,请尝试以下操作:
HashMap map = new HashMap();
public void parse(String foo) {
String foo2 = foo.substring(1, foo.length() - 1); // hack off braces
StringTokenizer st = new StringTokenizer(foo2, ",");
while (st.hasMoreTokens()) {
String thisToken = st.nextToken();
StringTokenizer st2 = new StringTokenizer(thisToken, "=");
map.put(st2.nextToken(), st2.nextToken());
}
}
String getValue(String key) {
return map.get(key).toString();
}
Run Code Online (Sandbox Code Playgroud)
警告:我实际上没有尝试过这个; 可能存在轻微的语法错误,但逻辑应该是合理的.请注意,我也完成了零错误检查,因此您可能希望使我做得更强大.