c-使用sscanf进行读取,直到找到序列



我会使用strchr,但我想找到一个序列,它看起来像这样:"%c"-包括空格。

但我有两个问题:

  • 是否可以匹配一个序列,而不是一组字符
  • 你能匹配像"[^%c]"这样的格式说明符吗?当然这不起作用,而且我找不到任何深入该格式的文献

目标是将未定义数量的字符串(组合后不超过缓冲区大小(读取到单个缓冲区中,直到找到一个空格分隔的字符:

char buf[50];
sscanf("string1 string2 string3 M other input", "%[^ %c ]", buf);
printf("%s", buf); //This would output "string1 string2 string3"

strchr可以找到字符串中第一个出现的字符。图案的末端可以通过比较第一非空间ch和第二非空间ch之间的距离来找到。

#include <stdio.h>
#include <string.h>
// The input buffer must match the pattern "string string ... ch"
const char* get_endof_pattern(const char *buffer)
{
const char *first_non_space = buffer;
const char *second_non_space = strchr(first_non_space, ' ') + 1;
if (!second_non_space)
return NULL;
while (second_non_space - first_non_space > 2) {
first_non_space = second_non_space;
second_non_space = strchr(first_non_space, ' ') + 1;
if (!second_non_space)
return NULL;
}
return first_non_space;
}

strspnstrcspn可用于查找被空格包围的单个字符。

#include <stdio.h>
#include <string.h>
int main( void) {
char *text[] = { "string1 string2 string3 M other input"
, "string1 string2 string3 other input M"
, "M string1 string2 string3 other input M"};
int offset = 0;
int spaces = 0;
int length = 0;
for ( int each = 0; each < 3; each++) {
offset = 0;
do {
spaces = strspn ( text[each] + offset, " ");//consecutive spaces
offset += spaces;
length = strcspn ( text[each] + offset, " ");//consecutive not space
offset += length;
} while ( 1 != length && 0 != *(text[each] + offset));
if ( 1 == length) {
printf ( "[%.*s]n", offset - ( spaces + length), text[each]);
}
else {
printf ( "[%s]n", text[each]);
}
}
return 0;
}

最新更新