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_r
和 regex.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/