分流/解析,并从字符数组获得价值 [英] split/parse and get value from a char array
本文介绍了分流/解析,并从字符数组获得价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用C编写的函数,通过它我可以从一个字符数组:
I want to write a function in C, by which I can get value of the tag from a char array ::
例:
char a[]="name=RRR&school=AAA&roll=111&address=SSS";
我想编写一个函数 - 如果我给名作为函数的参数则函数将返回RRR ---如果我给学校作为函数的参数则函数将返回AAA
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
我已经在Java中做到了......
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;
}
如何给它C 17没有简单的库或函数??
推荐答案
例如:
#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;
}
这篇关于分流/解析,并从字符数组获得价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文