我需要使用 c 从 "mac": "11:22:33:44:55:66"
这样的字符串中解析 mac 地址。
我的代码:
#include <stdio.h>
#include <string.h>
#include <stddef.h>
int main() {
char str[50] = "\"mac\" : \"11:22:33:44:55:66\"";
char second_string[20];
sscanf(str, "what should come here?", second_string);
printf("%s\n", second_string);
}
我的输出应该是:
11:22:33:44:55:66
最佳答案
scanf
family of functions进行简单模式匹配。因此你可以做类似的事情
sscanf(str, "\"mac\" : \"%[^\"]\"", second_string);
"%[^"
格式匹配任何除了结束"]"
之前的字符。
对于更通用的解决方案,您可以找到分隔符 ':'
(例如使用 strchr
)并且只解析字符串的最后部分(在 ':' 之后)
)。
为了更加通用,跳过冒号和所有空格(使用循环和 isspace
),这将只留下 "\"11:22:33:44:55:66\""
进行解析。这可以使用如上所示的 "%[^"
格式来完成。
关于c - 如何解析用 C 引号引起来的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53229688/