【问题标题】:Extracting integers from a query string从查询字符串中提取整数
【发布时间】:2013-08-26 01:15:18
【问题描述】:

我正在创建一个可以通过 C 和 html 进行 mysql 事务的程序。

我有这个查询字符串 query = -id=103&-id=101&-id=102&-act=Delete

通过 sscanf 提取“删除”并不难,但我需要帮助提取整数并将它们放入 int id[] 的数组中。 -id 条目的数量可能会有所不同,具体取决于在 html 表单中选中了多少复选框。

我一直在寻找几个小时,但没有找到任何适用的解决方案;或者我只是不明白他们。有什么想法吗?

谢谢

【问题讨论】:

    标签: html c forms query-string


    【解决方案1】:

    您可以使用strstratoi 在循环中提取数字,如下所示:

    char *query = "-id=103&-id=101&-id=102&-act=Delete";
    char *ptr = strstr(query, "-id=");
    if (ptr) {
        ptr += 4;
        int n = atoi(ptr);
        printf("%d\n", n);
        for (;;) {
            ptr = strstr(ptr, "&-id=");
            if (!ptr) break;
            ptr += 5;
            int n = atoi(ptr);
            printf("%d\n", n);
        }            
    }
    

    Demo on ideone.

    【讨论】:

    • 它只适用于捕获“id”......你可以简化一点(通过寻找“-id”而不是“&-id”)......但我喜欢它:)
    【解决方案2】:

    您想使用strtok 或更好的解决方案,用&= 作为标记来标记这个字符串。

    查看cplusplus.com 了解更多信息和示例。

    这是您将从 strtok 获得的输出

    Output:
    
    Splitting string "- This, a sample string." into tokens:
    This
    a
    sample
    string
    

    一旦弄清楚如何拆分它们,下一个障碍就是将数字从字符串转换为ints。为此,您需要查看atoi 或其更安全更强大的表亲strtol

    【讨论】:

    • 你可能应该提到strtol,因为这也是他的问题的一部分。
    • 如果我使用strtok,是否可以将整数分配到 int 数组?
    • @Exphyre strtok 用于将字符串拆分为多个片段,然后由您在这些片段中找到整数,然后将它们转换并存储到数组中跨度>
    【解决方案3】:

    我很可能会编写一个小型词法扫描器来完成这项任务。意思是,我会根据代表一组可能输入的正则表达式一次分析一个字符。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-30
      • 2020-07-20
      • 1970-01-01
      • 1970-01-01
      • 2019-09-14
      • 1970-01-01
      相关资源
      最近更新 更多