让我们有这段代码
char input[] = "key: value";
char key[32], value[32];
sscanf(input, "%31[^:]:%*[ ]%31s", key, value);
:
之后可以有零个或多个空格,我想将键和值存储到 c 字符串变量中。上面的代码可以使用一个或多个空格,但如果使用零个空格则运气不好。
有没有一种简单的方法来解析这样的字符串?不一定是 sscanf,但我想避免使用正则表达式。
编辑
我找到了一个 reference支持已接受的答案(多么有用但不直观的功能):
the function will read and ignore any whitespace characters encountered before the next non-whitespace character (whitespace characters include spaces, newline and tab characters -- see isspace). A single whitespace in the format string validates any quantity of whitespace characters extracted from the stream (including none).
最佳答案
只需使用 "%31[^:]:%31s"
。
%s
转换规范无论如何都会跳过前导空白,并在一个或多个非空白之后的第一个空白处停止。
如果您决定在第二个字段中需要空格,但不需要前导空格,则使用:
"%31[^:]: %31[^\001]"
(假设您的字符串不太可能包含您感兴趣的 control-A 字符)。格式字符串中的空格会跳过零个或多个空格(严格来说,零个或多个空白字符)。
关于c - 使用 sscanf 匹配零个或多个空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27612009/