split/parse and get value from a char array
21,333
Solution 1
strtok is what your are looking for.
Example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* getTagValue(char* a_tag_list, char* a_tag)
{
/* 'strtok' modifies the string. */
char* tag_list_copy = malloc(strlen(a_tag_list) + 1);
char* result = 0;
char* s;
strcpy(tag_list_copy, a_tag_list);
s = strtok(tag_list_copy, "&");
while (s)
{
char* equals_sign = strchr(s, '=');
if (equals_sign)
{
*equals_sign = 0;
if (0 == strcmp(s, a_tag))
{
equals_sign++;
result = malloc(strlen(equals_sign) + 1);
strcpy(result, equals_sign);
}
}
s = strtok(0, "&");
}
free(tag_list_copy);
return result;
}
int main()
{
char a[]="name=RRR&school=AAA&roll=111&address=SSS";
char* name = getTagValue(a, "name");
char* school = getTagValue(a, "school");
char* roll = getTagValue(a, "roll");
char* address = getTagValue(a, "address");
char* bad = getTagValue(a, "bad");
if (name) printf("%s\n", name);
if (school) printf("%s\n", school);
if (roll) printf("%s\n", roll);
if (address) printf("%s\n", address);
if (bad) printf("%s\n", bad);
free(name);
free(school);
free(roll);
free(address);
free(bad);
return 0;
}
Solution 2
Check the strtok
function out. You can use it to split your toSplit
string on &
and on each iteration split again on =
to see if the tag matches what you want.
Author by
Ronin
Updated on January 21, 2020Comments
-
Ronin over 4 years
I want to write a function in C, by which I can get value of the tag from a char array ::
Example ::
char a[]="name=RRR&school=AAA&roll=111&address=SSS";
I want to write a function - if I give "name" as a parameter of the function then the function will return RRR --- if I give "school" as a parameter of the function then the function will return AAA
i have done it in Java ...
public String getTagValue(String toSplit, String tag) { String CommandTypeValue=""; String[] FirstSplit; String[] SecondSplit; String delims = "&"; FirstSplit = toSplit.split(delims); for(int i=0; i<FirstSplit.length; i++ ) { delims = "="; SecondSplit = FirstSplit[i].split(delims); if(SecondSplit[0].equals(tag)) return SecondSplit[1]; //System.out.println(SecondSplit[0] +" "+ SecondSplit[1]); } return CommandTypeValue; }
How to do it C ?? any easy library or function ??