使用以下分隔符和子分隔符我找不到一种方法来检索作为整个字符串的issuer值,因为我已声明“,”作为字符串分隔符的一部分。 请帮忙。
输入字符串是一个char *数组:(抱歉,字符串是证书)
{"first name":"Jhon","thumbprint":"*********","issuer":"CN=dccw, OU=cswde, O=xswe,
L=sdewc","validto":"Mon Jan 01 22:59:59 EST
2018","lastname":"Doe","userid":"DJhon","valid from":"Mon Aug 15
00:00:00 EDT 2011","subjectInfor":"************"}
代码
char* delim = "{}";
char* subdelim = ":,";
char *str1, *token, *name, *value;
int parse_count = 0;
for (str1 = stringToParse; parse_count<num ; str1 = NULL) {
token = strtok(str1, delim);
if (token == NULL)
break;
name = strtok(token, subdelim);
value = strtok(NULL, subdelim);
if (name == NULL || value == NULL) {
continue;
}
strcpy (ptr->name, name);
strcpy (ptr->value, value);
ptr++;
parse_count++;
}
return name_values;
}
输出:
printf("%s=%s\n", params->name, params->value);
first name=Jhon
last name=Doe
userid=DJhon
答案 0 :(得分:1)
我认为最好使用JSON库,但是使用sscanf可以进行简单的解析。
#include <stdio.h>
#include <string.h>
int main(void){
char data[]="{\"first name\":\"Jhon\",\"thumbprint\":\"*********\",\"issuer\":\"CN=dccw, OU=cswde, O=xswe, L=sdewc\",\"validto\":\"Mon Jan 01 22:59:59 EST 2018\",\"lastname\":\"Doe\",\"userid\":\"DJhon\",\"valid from\":\"Mon Aug 15 00:00:00 EDT 2011\",\"subjectInfor\":\"************\"}";
char *contents = strtok(data, "{}");//remove '{' and '}' : note that is not included in the content
char key[128], value[128];
int len;
while(2==sscanf(contents, "\"%127[^\"]\":\"%127[^\"]\",%n", key, value, &len)){
if(!strcmp(key, "first name") || !strcmp(key, "lastname") || !strcmp(key, "userid"))
printf("%s=%s\n", key, value);
contents += len;
}
return 0;
}