分类目录归档:未分类

C/C++ key-value string parsing with strsep

#include <stdio.h>
#include <string.h>

void parse_key_value(char* str) {
    while (char* value = strsep(&str, "&")) {
        char* key = strsep(&value, "=");
        if (key != NULL && value != NULL) {
            printf("key %s value %s\r\n", key, value);
        }
    }
}

int main() {
    char stra[] = "&asd23&sd=900&c=0&";
    printf("%s\r\n", stra);
    parse_key_value(stra);
    
    char strb[] = "asd=23";
    printf("%s\r\n", strb);
    parse_key_value(strb);
    
    return 0;
}
output:
&asd23&sd=900&c=0&
key sd value 900
key c value 0
asd=23
key asd value 23