strtok of tabulator with 4 spaces C

3

I'm trying to parse a document, in which each line has strings separated by tabs (each tab > are 4 blank spaces), but when it comes to making a strtok I am not being able to recognize those blank spaces.

This is the code snippet in question:

if((toks[0] != '\r') && (toks[0] != '\n') && (toks[0] != '
hola----¿----que----tal----?
if((toks[0] != '\r') && (toks[0] != '\n') && (toks[0] != '
hola----¿----que----tal----?%pre%0%pre%0
0')){ while ((toks = strtok(NULL, " ")) != NULL){ if ((strcmp(toks, "\r\n") != 0) && (strcmp(toks, "\r") != 0) && (strcmp(toks, "\n") != 0)){ i++; inputs = realloc(inputs,i*sizeof(char*)); inputs[i-1] = toks; numArgs++; } } }
0%pre%0
0')){ while ((toks = strtok(NULL, " ")) != NULL){ if ((strcmp(toks, "\r\n") != 0) && (strcmp(toks, "\r") != 0) && (strcmp(toks, "\n") != 0)){ i++; inputs = realloc(inputs,i*sizeof(char*)); inputs[i-1] = toks; numArgs++; } } }

I am not able to do the strtok of while to recognize me the 4 spaces, an example of line that should be able to parsear is:

%pre%

Where each ' - ' represents a character ' '

Thank you very much in advance.

    
asked by D_94 21.12.2018 в 12:57
source

1 answer

2

It does not work for you because strtok( ) is not used like this:

  

char * strtok (char * str, const char * delim);

  Parameters:
str - pointer to the null-terminated byte string to tokenize
delim - pointer to the null-terminated byte string identifying delimiters

In delim you pass a pointer to a list of characters ; you can pass, for example, "abc" , and you will separate by any of them , a , b or c . But will not find you abc .

To search for a repeated character set , one possible option is to use strstr( ) , which will look for a chain within another , which is what you really want to do. Using it, going through a chain looking for separations is very simple:

char *ptr = "una cadena    de    texto";
while( ptr = (strstr( ptr, "    " ) ) ) {
  ptr += 4; // Nos saltamos los 4 espacios iniciales.

  // Hacemos lo que queramos hacer ...
}

Since not is equivalent to strtok( ) , to be able to chop a string you have to make some changes to our method:

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

int main( void ) {
  const char buff[] = "  Esto  no  es  mas  que  una  simple  cadena  de  prueba  ";

  const char *start = strstr( buff, "  " );

  if( start == buff ) start += 2; // Tamaño de los espacios.

  while( 1 ) {
    const char *end = strstr( start, "  " );

    if( !end ) break;

    printf( "%.*s\n", (int)( end - start ), start );
    start = end + 2; // Tamaño de los espacios
  }

  if( *start ) printf( "%s\n", start );

  return 0;
}
    
answered by 21.12.2018 / 13:22
source