如果我想让它变成4个单词,我如何处理这个字符串。如果我使用sscanf,它会将单词'Face mask‘一分为二。或者,是否可以使用sscanf以某种方式防止这种情况发生?
输入:
2021-01-01 2021-7-1 'Face masks' "Wear everywhere"
2000-08-05 2010-8-8 LOCKDOWN 'xxxxx'
输出:
2021-01-01
2021-7-1
'Face masks'
"Wear everywhere"
....
发布于 2021-02-04 20:44:15
由于存在可选的引号和可能的空词(''
或""
),scanf()
的功能不足以满足您的需要。
这是一个通用的手工编码解析器:
#include <stdio.h>
#include <string.h>
// split a string into up to count words stored in a 2D array of char
int split(char output[][100], int count, const char *str) {
// recognises space separated words and quoted content without
// embedded quotes of the same type. Quotes are stripped in output.
for (int i = 0; i < count; i++) {
const char *start;
int len;
str += strspn(str, " \t\f\v\r\n");
if (*str == '\0')
return i;
if (*str == '\'') {
start = ++str;
len = strcspn(str, "\'");
str += len;
str += (*str == '\'');
} else
if (*str == '\"') {
start = ++str;
len = strcspn(str, "\"");
str += len;
str += (*str == '\"');
} else {
start = str;
len = strcspn(str, " \t\f\v\r\n");
str += len;
}
snprintf(output[i], sizeof(output[i]), "%.*s", len, start);
}
}
https://stackoverflow.com/questions/66045637
复制相似问题