Autor Tema: Funcion strok por strsep  (Leído 1178 veces)

0 Usuarios y 1 Visitante están viendo este tema.

Desconectado cvargcal

  • PIC16
  • ***
  • Mensajes: 166
Funcion strok por strsep
« en: 26 de Marzo de 2019, 18:03:18 »
Saludos, necesito separar una cadena "a,b,,d" y luego imprimir 0 donde no haya datos.
a
b
0
d

Alguna idea?, si uso strok, el no imprime campos vacíos.



Código: C
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4.  
  5. int split(float *res , char *string , char delim);
  6.  
  7. int split(float *res , char *string , char delim){
  8. int strLen = 0;
  9. int commaCount =0;    // count the number of commas
  10. int commaCountOld =0; // count the number of commas
  11. int wordEndChar = 0;
  12. int wordStartChar = -1;
  13. int wordLength =0;
  14.  
  15.    for(strLen=0; string[strLen] != '\0'; strLen++){     // first get the string length
  16.        if ( (string[strLen] == delim)  || ( string[strLen+1] == '\0' ))        {
  17.            commaCount++;
  18.            wordEndChar = strLen;
  19.         }
  20.        if ( (commaCount - commaCountOld) > 0 )        {
  21.           int aIter =0;
  22.           wordLength = (wordEndChar - wordStartChar);
  23.           char word[55] = "";
  24.           for (aIter = 0;  aIter < wordLength; aIter++)          {
  25.             word[aIter] = string[strLen-wordLength+aIter+1];
  26.           }
  27.  
  28.           if (word[aIter-1] == delim)   word[aIter-1] = '\0';
  29.           //  printf("\n");
  30.           word[wordLength] = '\0';
  31.           res[commaCount-1] = atof(&word[0]);
  32.           wordLength = 0;
  33.           wordStartChar = wordEndChar;
  34.           commaCountOld = commaCount;
  35.         }
  36.   }
  37.   return commaCount;
  38. }
  39.  
  40.   void main(){
  41.     char string[] = "1,,3"; // specify input here
  42.     float array_r[10]; // specify size of float array here
  43.     int totalValues = 0;
  44.     char myDelim = ','; // specify delimiter here
  45.     printf("string => %s \n",&string[0]);
  46.     totalValues = split(&array_r[0] , &string[0], myDelim); // call the function here
  47.     int tokens = 0;
  48.  
  49.     for (tokens = 0 ; tokens < totalValues ; tokens++)    {
  50.       printf("array_r[%d] = %0.f\n",tokens , array_r[tokens]);
  51.     }
  52.  }

salida

string => 1,,3
array_r[0] = 1
array_r[1] = 0
array_r[2] = 3


alguna sugerencia para que no sea flotante sino un char

« Última modificación: 28 de Marzo de 2019, 13:39:15 por cvargcal »