拆分/解析并从char数组中获取值

时间:2012-01-20 12:07:21

标签: c parsing split

我想在C中编写一个函数,通过它我可以从char数组中获取标记的值::

示例::

char a[]="name=RRR&school=AAA&roll=111&address=SSS";

我想编写一个函数 - 如果我将“name”作为函数的参数,那么函数将返回RRR ---如果我将“school”作为函数的参数,那么函数将返回AAA < / p>

我用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 ??任何简单的库或函数??

4 个答案:

答案 0 :(得分:4)

strtok正是您所寻找的。

示例:

#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;
}

答案 1 :(得分:1)

检查strtok功能。您可以使用它在toSplit上分割&字符串,并在=上再次拆分每次迭代,以查看代码是否符合您的要求。

答案 2 :(得分:0)

使用标准库的strtok()系列: http://www.cplusplus.com/reference/clibrary/cstring/strtok/

答案 3 :(得分:0)

  char * p[10], temp;
  temp = strtok(str,"&");
  int i=0;
  while (temp != NULL)
  {
    p[i++] = temp;
    temp = strtok (NULL, "&");
  }

然后,您可以使用"="作为分隔符,分别对每个参数使用strtok。