Posts

Showing posts from June, 2022

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 ','.#includeiostream #include cstring; #include unordered_map; using namespace std; int main(int arg,char**argv){ string s="key1:value1,key2:value2,key3:value3,"; unordered_mapstring,string;kv ; bool k=0; string key,value; for (int i=0;is.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 s...

Tokenizing a string in C++

 Tokenizing a string using c /c++ Below is the code for c/c++ this a function works for me in c++. If any problem comment below.  the string str[] variable string is declared out side of function passed to function to store the tokens in the string array.remember to allocate sufficient or more space Required parameters for function : char str[],string s[],const char t 1 parameter: str[] is the string which you wanted to tokenize. 2 parameter : s[] is string arrray used to store the token.Declare it before function passed; 3 parameter:  t is char character at which the string should be tokenize(); Return value: none  look function and sample code below. Function: void tokenize(char str[],string s[],const char t){int i=0; string token;int j=0;int len=strlen(str); for(int i=0;i< len;i++){ if (str[i]== t ){ s[j]=token;j++;token=" "; }else{token.push_back(str[i]);} if (i==len-1){s[j]=token;} } } sample code for testing(c++)...