Hi guys i have a string "key={value}&key2={value2}&key3={value3}"
and have to produce a key-value pair of the string by splitting &
and =
. Also i have to watch out for corner cases such that if a key isn't present do not add it to the hash map but if a value is missing the key can be added with an empty value. One way is to first split the string by &
and finally by =
. So this can be accomplished but having two passes. But i am attempting to accomplish this in one pass.
First idea: I came up with one pass using the split function using but it didn't account for corner cases.
public Map<String, String> splitString(String s) {
// String s represents ParamAndMacro
String[] split = s.split("=|\\&");
int length = split.length;
Map<String, String> maps = new HashMap<>();
for (int i=0; i<length; i+=2){
maps.put(split[i], split[i+1]);
}
return maps;
}
Second Idea: One pass with certain conditions and using stringbuilder:
public Map<String, String> splitString(String s){
Map<String, String> maps = new HashMap<>();
int length = s.length();
StringBuilder sb = new StringBuilder();
String key = "";
String value = "";
char prev = ' ';
for (int i=0; i<length; i++) {
char a = s.charAt(i);
if ( a != '=' && a != '&' && prev != a) {
sb.append(a);
}
//finds a key
else if( a == '=' && prev != a && prev != '&') {
key = sb.toString();
sb = new StringBuilder();
}
// finds a value and also ensuring a key is not empty
else if (a=='&' && prev != a && prev != '=') {
value = sb.toString();
sb = new StringBuilder();
maps.put(key, value);
}
// checks corner case to see if a value is empty
else if (prev=='=' && a == '&') {
value = "";
maps.put(key, value);
sb = new StringBuilder();
}
//how to check if a key is missing and skip to other pair
prev = a;
}
return maps;
}
My question is my code efficient in terms of splitting and using stringbuilder. Please feel free to improve or give suggestions.