使用 sscanf 读取直到找到序列

Use sscanf to read until a sequence is found

我会使用 strchr 但我想找到一个序列,看起来像这样:“ %c ” - 包括 spaces。

但是我有两个问题:

目标是将未定义数量的字符串(合并后不超过缓冲区大小)读入单个缓冲区,直到找到单个 space 分隔字符:

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

strchr可以找到字符串中某个字符的第一次出现。通过比较第一个非space 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;
}