Split string into key-value pairs using C++

This is a small post  how to get key value pairs form a string which out any using any libraries 

if the string is 


string s ="key1:value1,key2:value2,key3:value3,

this is a string which we should parse where key value are seperated with ':' and key value pairs are seperated with ','.

#include<iostream>
#include <cstring>
#include <unordered_map>

using namespace std;
int main(int arg,char**argv){
	 string s="key1:value1,key2:value2,key3:value3,";

	 unordered_map<string,string>kv ;

	 bool k=0;
	 string key,value;
	 for (int i=0;i<s.length();i++){ 
		 if (s.at(i)==':')
			 k=1;
		 else if(s.at(i)==','){
			 kv[key] = value;
			 key="";value="";k=0;}
		 else if (k==0)
			key+=s[i];
		else
			 value+=s[i];
		 }
         cout<<kv["key1"]<<'\n'<<endl;
return 0;
}

form the above program Your can clearly see that the program will parse the string and place the values in an unordered_map class which is speed made with hashTable internally.Advantages of using a unordered_map is that it is very fast and we can store,access,find,erase the key and value pairs easily

the above program will output value1.Because we are trying to access the value for the key1

No comments: