【问题标题】:extracting an unknown substring out of a string从字符串中提取未知子字符串
【发布时间】:2012-02-28 09:16:00
【问题描述】:

我有一个程序以以下格式返回数据:

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

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

知道怎么做吗?代码 sn-ps 表示赞赏。

【问题讨论】:

  • 您需要指定如何识别要提取的十六进制值,因为有多个。但是如果你能找到它,你可以将 sscanf 扔到以你想要的位开头的字符串上。
  • 我尝试使用 strstr 传递 bytes = 然后 sscanf 但没有得到任何结果。你有我可以玩的sn-p代码吗?

标签: c substring


【解决方案1】:

您可以使用strstr() 在输入字符串中定位“bytes = 0x”并复制字符串的其余部分(从“bytes = 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;
}

【讨论】:

    【解决方案2】:

    您可以使用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 不可重入。

    【讨论】:

      猜你喜欢
      • 2014-07-26
      • 1970-01-01
      • 1970-01-01
      • 2011-07-21
      • 1970-01-01
      • 2020-05-14
      • 2018-09-29
      • 2021-12-23
      相关资源
      最近更新 更多