2012-02-06 75 views
1

我有一个程序以下列格式返回数据:提取未知子出串

<CFData 0x1001219c0 [0x7fff7027aee0]>{length = 20, capacity = 20, bytes = 0x8deead13b8ae7057f6a629fdaae5e1200bcb8cf5} 

我需要提取8deead13b8ae7057f6a629fdaae5e1200bcb8cf5(是的,减去0x)。我尝试使用sscanf并传递一些正则表达式,但我不知道这一点。

任何想法如何做到这一点?代码片断表示赞赏。

+0

您需要指定如何识别您希望提取的十六进制值,因为有多个值。但是如果你能找到它,你可以在你想要的位开始的时候将sscanf放在字符串处。 – 2012-02-06 21:58:30

+0

我试着用'strstr'传递'bytes ='然后'sscanf',但没有到任何地方。你有我可以玩的代码片段吗? – 2012-02-06 22:00:43

回答

5

你可以使用strstr()输入字符串来定位“字节= 0X”,并复制字符串的其余部分(从“字节= 0x”为结束),除了最后一个字符:

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

感谢您的帮助 – 2012-02-07 15:13:54

1

你可以使用strtok来完成这个技巧。

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

请注意,这只是一个示例。您应该强烈考虑使用strtok_r来重写此内容,因为strtok不可重入。