c - 使用 sscanf 匹配零个或多个空格

标签 c string parsing scanf

让我们有这段代码

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/

相关文章:

c++ - Windows Python C 扩展仅适用于我自己的 Python 构建(使用 VC++ 2008 Express 的 32 位构建)

arrays - 如何通过特定字符分隔 Swift 3 中的字符串

string - 如何通过正则表达式 3 和 4 字节 UTF-8 进行匹配

php - 将 float 格式化为两位小数

parsing - yacc 可以解析哪一类语言?

parsing - 搜索工具/指南来读取 1998 年文件( "magic number"SFS)

c - 二维结构数组 -> 无法修复段错误 :(

c - 在 C if 语句中检查 NULL 时最好使用 OR 或 AND?

c - 如何在 C 中将连续数组作为参数传递?

c++ - 右递归文法还是左递归文法?