我想将以下文本分解为字符串:
John, Smith, 10 Maple Street, Cullowhee, NC, 28779, 828.123.4567
Susan, thompson, 21 Oak Road, Webster, NC, 28711, 828.434.3232
Sarah, foster, 32 Sycamore Street, Sylva, NC, 28712, 828.112.3456
bruce, Hampton, 321 Linden Street, Dillsboro, NC, 28123, 828.432.7895
Bill, Thompson, 141 Cedar Drive, Sauk City, WI, 43214, 415.323.2254
这是我到目前为止所拥有的:
void sort(FILE* in, FILE* out){
char buffer[LINE_LENGTH];
int i = 0;
int j = 0;
while(fgets(buffer, sizeof(buffer), in) != NULL) {
sscanf(buffer , "%[^,],%[^,],%[^,],%[^,],"
"%[^,],%[^,],%[^,]",
str1, str2, str3, str4, str5, str6, str7);
i++;
}
无论我做什么,我似乎都无法摆脱 Susan
和 Bill
前面的空格/制表符。我不确定需要对 sscanf(buffer , **"%[^,]**
这第一个正则表达式进行哪些更改来删除这些空格。我尝试过 [^a- zA-Z]
在第一个 %[^,]
前面,尝试将 %[^,]
替换为 %[^ ,] , % [^' ',], %[^'\t',]
。此更改要么不执行任何操作,要么使所有字符串消失,仅 ,,,,,,,,,,,,,,, ,,,,,,,,,
出现在控制台上。
最佳答案
*scanf
格式字符串中的空白字符指示 *scanf
读取并丢弃任意数量的空白字符(如果有),直到第一个非空白字符.
这可以在 C11 标准中看到:
7.21.6.2 The
fscanf
function[...]
- A directive composed of white-space character(s) is executed by reading input up to the first non-white-space character (which remains unread), or until no more characters can be read. The directive never fails.
因此,只需在所有 %[
之前添加一个空格,以便修剪掉前导空白字符。
注意:最后一个 %[^,]
需要更改为 %[^\n]
,因为该行后面没有任何逗号。
关于c - 如何在 sscanf() 中使用 RegEx 以特定方式在 c 中标记字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35724767/