java - Efficient way to split a string in one pass to produce a key value pair and check corner case if key is empty -


hi guys have string "key={value}&key2={value2}&key3={value3}" , have produce key-value pair of string splitting & , =. have watch out corner cases such if key isn't present not add hash map if value missing key can added empty value. 1 way first split string & , =. can accomplished having 2 passes. attempting accomplish in 1 pass.

first idea: came 1 pass using split function using didn't account 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<>();     (int i=0; i<length; i+=2){           maps.put(split[i], split[i+1]);      }      return maps; } 

second idea: 1 pass conditions , 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 = ' '; (int i=0; i<length; i++) {     char = s.charat(i);     if ( != '=' && != '&' && prev != a) {            sb.append(a);               }     //finds key     else if( == '=' && prev != && prev != '&') {           key = sb.tostring();           sb = new stringbuilder();       }     // finds value , ensuring key not empty     else if (a=='&' && prev != && prev != '=') {           value = sb.tostring();           sb = new stringbuilder();           maps.put(key, value);             }     // checks corner case see if value empty     else if (prev=='=' && == '&') {           value = "";           maps.put(key, value);           sb = new stringbuilder();     }    //how check if key missing , skip other pair              prev = a;     }     return maps; } 

my question code efficient in terms of splitting , using stringbuilder. please feel free improve or give suggestions.


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -