Reputation: 1895
I have a program returning data in the following format:
<CFData 0x1001219c0 [0x7fff7027aee0]>{length = 20, capacity = 20, bytes = 0x8deead13b8ae7057f6a629fdaae5e1200bcb8cf5}
I need to extract 8deead13b8ae7057f6a629fdaae5e1200bcb8cf5
(yes, minus the 0x
). I tried using sscanf
and passing some regular expressions but I have no clue on that.
Any idea how to do this? Code snippets are appreciated.
Upvotes: 1
Views: 539
Reputation: 121971
You could use strstr() to locate "bytes = 0x" in the input string and copy the remainder of the string (from the end of "bytes = 0x") except for the last character:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char* s = "<CFData 0x1001219c0 [0x7fff7027aee0]>{length = 20, "
"capacity = 20, "
"bytes = 0x8deead13b8ae7057f6a629fdaae5e1200bcb8cf5}";
char* value = 0;
const char* begin = strstr(s, "bytes = 0x");
if (begin)
{
begin += 10; /* Move past "bytes = 0x" */
value = malloc(strlen(begin)); /* Don't need 1 extra for NULL as not
copy last character from 'begin'. */
if (value)
{
memcpy(value, begin, strlen(begin) - 1);
*(value + strlen(begin) - 1) = 0;
printf("%s\n", value);
free(value);
}
}
return 0;
}
Upvotes: 5
Reputation: 726539
You can use strtok
to do the trick.
int main(int argc, char* argv[]) {
char s[] = "<CFData 0x1001219c0 [0x7fff7027aee0]>{length = 20, capacity = 20, bytes = 0x8deead13b8ae7057f6a629fdaae5e1200bcb8cf5}";
const char *tok = "<>[]{}= ,";
char* t = strtok(s, tok);
int take_next = false;
char * res;
while (t) {
if (take_next) {
res = t+2;
break;
}
take_next = !strcmp(t, "bytes");
t = strtok(NULL, tok);
}
printf("%s\n", res);
return 0;
}
Note that this is only a sample. You should strongly consider rewriting this using strtok_r
, because strtok
is not re-entrant.
Upvotes: 1