c - 是否有 sscanf 的变体,它带有指向输入字符串而不是缓冲区的指针?

标签 c parsing scanf tokenize

sscanf 是这样工作的:

int main(const int argc, const char *argv[]) {
    char buf1[1024] = {0};
    char buf2[1024] = {0};
    char buf3[1024] = {0};
    char *str = "abc, 123; xyz";
    sscanf(str, "%[^,], %[^;]; %s", buf1, buf2, buf3);
    printf("'%s' '%s' '%s'", buf1, buf2, buf3); // Prints: "'abc' '123' 'xyz'"
    return 0;
}

我想知道是否有一个函数不需要将 str 的内容复制到缓冲区(buf1、buf2、buf3),也不需要分配任何新的内存。相反,它只是将指针(ptr1、ptr2、ptr3)设置为指向 str 中的匹配部分,并且 null 终止匹配之后的任何内容。

int main(const int argc, const char *argv[]) {
    char *ptr1 = NULL;
    char *ptr2 = NULL;
    char *ptr3 = NULL;
    char *str = "abc, 123; xyz";
    //
    // str = "abc, 123; xyz\0"
    //
    _sscanf(str, "%[^,], %[^;]; %s", &ptr1, &ptr2, &ptr3);
    //
    // str = "abc\0 123\0 xyz\0"
    //        ^     ^     ^
    //       ptr1  ptr2  ptr3
    //
    printf("'%s' '%s' '%s'", ptr1, ptr2, ptr3); // Prints: "'abc' '123' 'xyz'"

    return 0;
}

我知道可以使用 strtok_rregex.h 库等函数,但我认为这在输入字符串的情况下会更方便可以修改。

最佳答案

它并不漂亮,但 %n 说明符可用于捕获标记开始和结束的索引。错误检查将确保索引和结束值不是 -1

#include <stdio.h>

int main(int argc, char *argv[]) {
    int index1 = -1;
    int end1 = -1;
    int index2 = -1;
    int end2 = -1;
    int index3 = -1;
    int end3 = -1;
    char *str = "abc, 123; xyz";
    sscanf(str, " %n%*[^,]%n, %n%*[^;]%n; %n%*s%n", &index1, &end1, &index2, &end2, &index3, &end3);
    printf("'%.*s' '%.*s' '%.*s'", end1, str + index1, end2 - index2, str + index2, end3 - index3, str + index3); // Prints: "'abc' '123' 'xyz'"
    return 0;
}

关于c - 是否有 sscanf 的变体,它带有指向输入字符串而不是缓冲区的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46379190/

相关文章:

C 和指针符号

c - 当你在一个用 dup2() 复制的管道文件描述符上调用 close() 时会发生什么?

jquery - $.parseJSON() 在有效对象上返回 null

c - sscanf 读入了错误的值

c - Stdin with getc 产生额外的输出,并打开文件导致 C 中的段错误

抛弃常量会导致未定义的行为吗?

parsing - 使用ANTLR分析和修改源代码;我做错了吗?

ruby - 解析具有不同分隔符的文本 - 带分组

c - 如何使用两个scanf避免用户输入越界?

c - 简单的C计算器错误