Pergunta

Como a sequência de tab-delimiter para analisar a segurança? Por exemplo: teste tbla-bla-bla t2332?

Foi útil?

Solução

strtok() é uma função padrão para analisar strings com delimitadores arbitrários. No entanto, não é seguro de linha. Sua biblioteca C de escolha pode ter uma variante segura para roscas.

Outra maneira compatível com o padrão (acabei de escrever isso, é não testado):

#include <string.h>
#include <stdio.h>

int main()
{
    char string[] = "foo\tbar\tbaz";
    char * start = string;
    char * end;
    while ( ( end = strchr( start, '\t' ) ) != NULL )
    {
        // %s prints a number of characters, * takes number from stack
        // (your token is not zero-terminated!)
        printf( "%.*s\n", end - start, start );
        start = end + 1;
    }
    // start points to last token, zero-terminated
    printf( "%s", start );
    return 0;
}

Outras dicas

Use STRTOK_R em vez do STRTOK (se estiver disponível). Tem uso semelhante, exceto que é reentrante, e não Modifique a string como o strtok. [[Editar: Na verdade, eu falei mal. Como Christoph aponta, Strtok_R substitui os delimitadores por ' 0'. Portanto, você deve operar em uma cópia da string se desejar preservar a string original. Mas é preferível a Strtok porque é reentrante e seguro de linha

Strtok deixará sua string original modificada. Ele substitui o delimitador por ' 0'. E se sua sequência for uma constante, armazenada em uma memória somente leitura (alguns compiladores farão isso), você pode realmente obter uma violação de acesso.

Usando strtok() a partir de string.h.

#include <stdio.h>
#include <string.h>

int main ()
{
    char str[] = "test\tbla-bla-bla\t2332";
    char * pch;
    pch = strtok (str," \t");
    while (pch != NULL)
    {
        printf ("%s\n",pch);
        pch = strtok (NULL, " \t");
    }
    return 0;
}

Você pode usar qualquer biblioteca regex ou até o glib GScanner, Vejo aqui e aqui Para maiores informações.

Mais uma versão; este separa a lógica em uma nova função

#include <stdio.h>

static _Bool next_token(const char **start, const char **end)
{
    if(!*end) *end = *start;    // first call
    else if(!**end)             // check for terminating zero
        return 0;
    else *start = ++*end;       // skip tab

    // advance to terminating zero or next tab
    while(**end && **end != '\t')
        ++*end;

    return 1;
}

int main(void)
{
    const char *string = "foo\tbar\tbaz";

    const char *start = string;
    const char *end = NULL; // NULL value indicates first call

    while(next_token(&start, &end))
    {
        // print substring [start,end[
        printf("%.*s\n", end - start, start);
    }

    return 0;
}

Se você precisar de uma maneira segura binária para tokenizar uma determinada string:

#include <string.h>
#include <stdio.h>

void tokenize(const char *str, const char delim, const size_t size)
{
        const char *start = str, *next;
        const char *end = str + size;

        while (start < end) {
                if ((next = memchr(start, delim, end - start)) == NULL) {
                        next = end;
                }

                printf("%.*s\n", next - start, start);
                start = next + 1;
        }
}

int main(void)
{
        char str[] = "test\tbla-bla-bla\t2332";
        int len = strlen(str);

        tokenize(str, '\t', len);

        return 0;
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top